2013年5月30日 星期四

iOS_save_Object

objective-c可以用NSKeyedArchiver將物件的狀態給存起來,紀錄一下
1. 流程:
   |- 要儲存的物件需要先confirm  protocol
   |- 實做兩個method(一定要implement)
- (id)initWithCoder:(NSCoder *)aDecoder;
- (void)encodeWithCoder:(NSCoder *)aCoder;
   |- save objective用->[NSKeyedArchiver archiveRootObject:array toFile:path];
   |- load objective用->[NSKeyedUnarchiver unarchiveObjectWithFile:path]; 
2. example:
Objective.h:
#import 

#define kEncodeKeyGridName @"kEncodeKeyName"
#define kEncodeKeyGridColor @"kEncodeKeyColor"
#define kEncodeKeyGridDate @"kEncodeKeyDate"

@interface UAGridState : NSObject

@property (strong,nonatomic)NSString *name;
@property NSInteger color;
@property (strong,nonatomic)NSString *date;

@end
Objective.m:
- (id)initWithCoder:(NSCoder *)aDecoder{
    
    if((self = [super init])){
        
        self.name = [aDecoder decodeObjectForKey:kEncodeKeyGridName];
        self.color = [aDecoder decodeIntegerForKey:kEncodeKeyGridColor];
        self.date = [aDecoder decodeObjectForKey:kEncodeKeyGridDate];
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder{
    
    [aCoder encodeObject:self.name forKey:kEncodeKeyGridName];
    [aCoder encodeInteger:self.color forKey:kEncodeKeyGridColor];
    [aCoder encodeObject:self.date forKey:kEncodeKeyGridDate];
}
AppDelegate.m:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{   
    //File url
    NSArray *urls = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory
                                                           inDomains:NSUserDomainMask];
    NSString *documentDirPath = [[urls objectAtIndex:0] path];
    NSString *path = [documentDirPath stringByAppendingPathComponent:@"tmpFile"];

    //using NSKeyedUnarchiver load data
    [UAViewControllerState sharedDataSource].viewControllerArray = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{   
    //File url
    NSArray *urls = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory
                                                           inDomains:NSUserDomainMask];
    NSString *documentDirPath = [[urls objectAtIndex:0] path];
    NSString *path = [documentDirPath stringByAppendingPathComponent:@"tmpFile"];

    //using NSKeyedArchiver save data
    NSMutableArray *array = [UAViewControllerState sharedDataSource].viewControllerArray;
    [NSKeyedArchiver archiveRootObject:array toFile:path];
}
reference1
reference2

沒有留言:

張貼留言