开发者

iPhone - accessing an NSArray in a ViewController from the AppDelegate?

I want to be able to access an array of objects in my iPhone application. The array of objects is populated in the appDelegate of my application and I want to be able to access the array in one of my View Controllers.

I currently set up the array in my appDelegate.h file as follows:

NSArray *listObjArray;
@property (nonatomic, retain) NSArray *listObjArray;

I then populate it with some Strings like this in the AppDelegate:

listObjArray = [NSArray arrayWithObjects:@"Hello", @"How", @"are", nil];
NSLog(@"Array size 开发者_如何转开发= %i", [listObjArray count]);

It is synthesized and also released in dealloc. The NSLog returns the correct count here.

In my ViewController class I import the appDelegate like this:

#import "MyaAppDelegate.h"

I then access my appDelegate and the NSArray like this and try to Log the count in my View Controller:

MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] 
                                       delegate];

NSLog(@"Before array set");
NSArray *newArray = [appDelegate listObjArray];
NSLog(@"After array set");
NSLog(@"array count = %i", [newArray count]);
NSLog(@"After array count");

The logging here gets to "After array set" and then I get "EXC_BAD_ACCESS" on the line where I try to print the count from the array in the View Controller.

The printing of the count works fine from the appDelegate and setting the newArray as the array from the delegate appears to work yet I cant do anything with it then.

Can anyone see what I am doing wrong?


I think your array declaration should be:

NSArray *newArray = [[NSArray alloc] initWithArray:appDelegate.listObjArray]

Be sure to release it after you are done! Though I'm not sure why you want to declare the new array, you could just do:

NSLog(@"array count = %i", [appDelegate.lstObjArray count]);

Hope this helps!

-Karoly


You have a memory issue: listObjArray = [NSArray arrayWithObjects:@"Hello", @"How", @"are", nil]; sets the instance variable directly. Shortly after this line the array gets released again, which results in you accessing a bad memory location in NSArray *newArray = [appDelegate listObjArray];, since it has been freed.

Use self.listObjArray = ... instead when populating the array. This will properly retain the object for you.


Please use the getter if it is sythesized. Since you are not using the getter, it is giving you bad memory access.

Also you should use retain or copy if you want to retain it or copy it. Else both newArray and listObjectArray will point to same memory location causing bad behavior.

NSArray *newArray = [[appDelegate getListObjArray] retain];


Try this

self.listObjArray = [NSArray arrayWithObjects:@"Hello", @"How", @"are", nil];

Allocation should be made on the getter.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜