Tutorial :How to Keep an NSArray in Memory as Long as App is Running


Can anybody tell me how to make sure an NSArray exist in memory as long as the app is running?



If you're trying to preserve the array until the application exits, allocate it in your App Delegate's -init method and release it in the App Delegate's -dealloc method. Unless you make a mistake in your memory management and release the array too many times, it will be available for the entire lifecycle of the application.

For example:

@interface MyApp <NSApplicationDelegate>  {    NSArray *myArray;  }  @end    @implementation MyApp    - (id)init  {    if (nil != (self = [super init]))    {      myArray = [[NSArray alloc] init];    }    return self;  }    - (void)dealloc  {    [myArray release], myArray = nil;    [super dealloc];  }    @end  


You can retain the object in application delegate class and on application terminate release.


in application delegate class

@interface MyAppDelegate : NSObject <UIApplicationDelegate>   {      UIWindow *window;      NSMutableArray *arrayObjects;  }  @property (nonatomic, retain) IBOutlet UIWindow *window;  @property (nonatomic, retain) NSMutableArray *arrayObjects;  

Now you can allocate the arrayObjects using the instance of delegate class and you can also use the value stored in arrays.

MyAppDelegate *appDelegate = (MyAppDelegate*)[[UIApplication sharedApplication]delegate];  appDelegate.arrayObjects = [[NSMutableArray alloc] initWithObjects:@"Object 1",@"Object 2",@"Object 3",nil];  

This will preserve value in your array.Now You can use array any where in application after proper initialization.


If I understand you correctly you want to store a NSArray instance to disk?

In that case use [NSKeyedArchiver archiveRootObject:myArray toFile:path]

The folder to store the file at can be determined with:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  NSString *documentsDirectory = [paths objectAtIndex:0];  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »