问题
Help me in adding objects in array of app delegate from UIViewController in Objective-C I guess I am doing mistake, help me in this regard
I want to add objects in array of app delegate from view controller
in appdelegate.h
@property (nonatomic, retain) NSMutableArray *sharedArray;
in appdelegate.m
@implementation AppDelegate
@synthesize sharedArray;
inside didfinishlaunching
self.sharedArray = [[NSMutableArray alloc] init];
in ViewController
@interface ViewController () {
UIApplication *appDelegate;
Inside viewdidload
of viewcontroller
appDelegate = [[UIApplication sharedApplication] delegate];
[appdelegate.sharedArray addObject:array];
回答1:
Change declaration of
UIApplication *appDelegate;
to
AppDelegate *appDelegate;
//
self.appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
// on top you should
#import "AppDelegate.h"
回答2:
Your code is fine and correct, but you need to initialize the memory of your array before append the object
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
self. sharedArray = [NSMutableArray array];
return YES;
}
finally call the method as
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[appDelegate.sharedArray addObject:array];
finally import the header
#import "AppDelegate.h"
来源:https://stackoverflow.com/questions/49773206/adding-objects-in-array-of-app-delegate-from-view-controller-in-objective-c-ios