Adding objects in array of app delegate from view controller in Objective-C iOS

妖精的绣舞 提交于 2019-12-11 14:14:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!