从 Objective-C iOS 中的视图控制器向应用程序委托数组中添加对象

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

帮助我在 Objective-C 中从 UIViewController 添加对象到应用程序委托数组中我想我做错了,在这方面帮助我

我想在视图控制器的应用委托数组中添加对象

在appdelegate.h

@property (nonatomic, retain) NSMutableArray *sharedArray;

在 appdelegate.m

@implementation AppDelegate
@synthesize sharedArray;

里面didfinishlaunching

self.sharedArray = [[NSMutableArray alloc] init];

在ViewController

@interface ViewController () {

    UIApplication *appDelegate;


viewcontroller

viewdidload
appDelegate = [[UIApplication sharedApplication] delegate];
[appdelegate.sharedArray addObject:array];

您的代码很好而且正确,但是您需要在附加 object

之前初始化数组的内存
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.

    self. sharedArray = [NSMutableArray array];

    return YES;
}

最后调用方法为

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
 [appDelegate.sharedArray addObject:array];

最后导入 header

#import "AppDelegate.h"

更改

的声明
UIApplication *appDelegate;

AppDelegate *appDelegate;

//

self.appDelegate =  (AppDelegate *)[[UIApplication sharedApplication] delegate];

// 在最上面你应该

#import "AppDelegate.h"