iPhone: Save / Load NSMutableArray of Custom Object from NSUserDefaults
Bookmark.h//
// Bookmark.h
// Mapjack
//
// Created by Benjamin Rafael F. Intal on 8/2/10.
// Copyright 2010 __MyCompanyName__. All rights reserved.
//
#import
@interface Bookmark : NSObject
NSString *name;
NSString *address;
NSString *position;
}
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *address;
@property (nonatomic, copy) NSString *position;
@end
//
// Bookmark.m
// Mapjack
//
// Created by Benjamin Rafael F. Intal on 8/2/10.
// Copyright 2010 __MyCompanyName__. All rights reserved.
//
#import "Bookmark.h"
@implementation Bookmark
@synthesize name;
@synthesize address;
@synthesize position;
- (id) initWithCoder: (NSCoder *)coder
{
self = [[Bookmark alloc] init];
if (self != nil)
{
self.name = [coder decodeObjectForKey:@"name"];
self.address = [coder decodeObjectForKey:@"address"];
self.position = [coder decodeObjectForKey:@"position"];
}
return self;
}
- (void) encodeWithCoder: (NSCoder *)coder
{
[coder encodeObject:name forKey:@"name"];
[coder encodeObject:address forKey:@"address"];
[coder encodeObject:position forKey:@"position"];
}
@end
localBookmarks = [[NSMutableArray alloc] init];
// Load from prefs
NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
NSData *dataRepresentingSavedArray = [currentDefaults objectForKey:@"bookmarks"];
if (dataRepresentingSavedArray != nil) {
NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingSavedArray];
if (oldSavedArray != nil)
localBookmarks = [[NSMutableArray alloc] initWithArray:oldSavedArray];
else
localBookmarks = [[NSMutableArray alloc] init];
}
Save procedure in controller:
NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
[currentDefaults setObject:[NSKeyedArchiver archivedDataWithRootObject: localBookmarks] forKey:@"bookmarks"];
[currentDefaults synchronize];
0 Comments:
Post a Comment
<< Home