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?
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 inNSArray *newArray = [appDelegate listObjArray];, since it has been freed.Use
self.listObjArray = ...instead when populating the array. This will properly retain the object for you.