iPhone:Store & Retrieve NSMutableArray object
appDelegate.categoryData = [NSMutableDictionary dictionaryWithObjectsAndKeys:
categoryStr, @"name",image ,@"image", nil];
[appDelegate.categories addObject:appDelegate.categoryData];
NSLog(@"Category Data:--->%@",appDelegate.categor开发者_运维技巧ies);
I am successfully added object mutabledictionary into mutuablearray but I want to store that array and retrieve when application is launched so please give me idea to develop this functionality.
Thanks in advance.
//you can save array in NSUserDefaults like below
if ([[NSUserDefaults standardUserDefaults] valueForKey:@"detail"]==nil)
{
NSMutableDictionary *dic_detail = [NSMutableDictionary dictionaryWithObjectsAndKeys:
categoryStr, @"name",image ,@"image", nil];
NSMutableArray *ary_detail = [[NSMutableArray alloc] init];
[ary_detail addObject:dic_detail];
[[NSUserDefaults standardUserDefaults] setObject:ary_detail forKey:@"detail"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
//if you want read that array you can read like below in your app
NSMutableArray *array = [[NSMutableArray alloc] initWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"detail"]];
- (void)applicationDidEnterBackground:(UIApplication *)application {
NSLog(@"applicationDidEnterBackground = %@",[[NSUserDefaults standardUserDefaults] objectForKey:@"detail"]);
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
NSLog(@"applicationWillEnterForeground = %@",[[NSUserDefaults standardUserDefaults] objectForKey:@"detail"]);
}
in my log its printing like this
applicationDidEnterBackground = (
{
image = img1;
name = cat1;
}
applicationWillEnterForeground = (
{
image = img1;
name = cat1;
}
Perhaps something like this:
NSMutableArray * array = [NSMutableArray array];
appDelegate.categoryData = [NSMutableDictionary dictionaryWithObjectsAndKeys:
categoryStr, @"name",
image ,@"image",
array, @"array", nil];
Something like:
On Application launch:
[[NSUserDefaults standardUserDefaults] registerDefaults:
[NSDictionary dictionaryWithObjectsAndKeys:
[NSArray new], @"StoredArray", nil]];
In your class that "owns" control of the array:
- (void)setArray:(NSMutableArray *)array {
[[NSUserDefaults standardUserDefaults] setObject:array forKey:@"StoredArray"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (NSArray*)array {
return [[[NSUserDefaults standardUserDefaults] arrayForKey:@"StoredArray"] mutableCopy];
}
Hope this helps!
精彩评论