
Question:
Can anybody tell me how to make sure an NSArray exist in memory as long as the app is running?
Thanks......
Solution:1
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
Solution:2
You can retain the object in application delegate class and on application terminate release.
i.e
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.
Solution:3
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
EmoticonEmoticon