Xcode 如何在app delegate中将对象存储到NSmutablearray?

Xcode 如何在app delegate中将对象存储到NSmutablearray?,xcode,nsmutablearray,Xcode,Nsmutablearray,我在app delegate中使用NSmutable array存储和访问对象时遇到问题。我曾尝试过其他网站的方法,并堆叠重叠页面,但没有解决方案。我希望能够在另一个视图中访问阵列数据。目前没有任何东西对我有效 这是我的密码 AppDelegate.h : @interface AppDelegate : UIResponder <UIApplicationDelegate> { NSMutableArray* sharedArray; } @property (non

我在app delegate中使用NSmutable array存储和访问对象时遇到问题。我曾尝试过其他网站的方法,并堆叠重叠页面,但没有解决方案。我希望能够在另一个视图中访问阵列数据。目前没有任何东西对我有效

这是我的密码

AppDelegate.h :


@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
    NSMutableArray* sharedArray;
}

@property (nonatomic, retain)  NSMutableArray* sharedArray;


ViewController.h :


#import "AppDelegate.h"

-(void)viewDidLoad{

 AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
            NSMutableArray *model = appDelegate.sharedArray;

            NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
            [dict setObject:@"hello" forKey:@"title"];

            [dict setObject:@"urlhere" forKey:@"thumbnail"];


            [model addObject:dict];


            NSLog(@"submitted to array: %@",model);

}
AppDelegate.h:
@接口AppDelegate:UIResponder
{
NSMutableArray*共享Darray;
}
@属性(非原子,保留)NSMutableArray*sharedArray;
ViewController.h:
#导入“AppDelegate.h”
-(无效)viewDidLoad{
AppDelegate*AppDelegate=(AppDelegate*)[[UIApplication sharedApplication]委托];
NSMutableArray*model=appDelegate.sharedArray;
NSMutableDictionary*dict=[[NSMutableDictionary alloc]init];
[dict setObject:@“你好”forKey:@“标题”];
[dict setObject:@“urlhere”forKey:@“缩略图”];
[模型添加对象:dict];
NSLog(@“提交到阵列:%@”,型号);
}

您是否在任何时候初始化
共享Darray
?必须先实例化该数组,然后才能向其中添加对象。例如:

AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.

    self.sharedArray = [NSMutableArray array];

    return YES;
}
完成后,现在尝试从视图控制器向该阵列添加对象应该会成功


不相关,但不应为属性定义实例变量。让编译器为您合成,例如:

AppDelegate.h:

@interface AppDelegate : UIResponder <UIApplicationDelegate>
// {
//     NSMutableArray* sharedArray;
// }

@property (nonatomic, retain)  NSMutableArray* sharedArray;

@end
@接口AppDelegate:UIResponder
// {
//NSMutableArray*共享Darray;
// }
@属性(非原子,保留)NSMutableArray*sharedArray;
@结束

您拥有的在技术上是可以接受的,但这是不可取的,因为这个
sharedArray
实例变量与编译器将为您合成的内容之间可能存在混淆(例如,如果您没有
@synthesis
行,编译器将自动为您创建一个名为
\u sharedArray
的实例变量,并带有一个前导下划线)。即使您有一个确保实例变量正确的
@synthesis
行,显式声明的实例变量也是多余的。

我猜您从未创建数组。因此在应用程序中,我只添加self.sharedArray=[NSMutableArray];是这样吗?@AlexH——不,你知道为什么要添加那句话或它的等价物。然后做你应该做的。