standwally

NSKeyedArchiver/NSKeyedUnarchiver 본문

프로그래밍/iOS

NSKeyedArchiver/NSKeyedUnarchiver

standwally 2013. 2. 28. 15:18

데이터를 보관하기 위한 용도로 쓰이는 클래스 입니다.

NSKeyedArchiver의 사용방법은 인코딩과 디코딩 단계로 이루어집니다.

1. Encoding

NSArray* array = [[NSArray alloc] initWithArray:NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)];
NSString* strPath = [NSString stringWithFormat:@"%@/KeyedArchive", [array objectAtIndex:0]];
    
NSString* str = [NSString stringWithFormat:@"Hello!!!"];
    
NSMutableData* mutableData = [NSMutableData data];
    
NSKeyedArchiver* archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:mutableData];
[archiver encodeObject:str forKey:@"Key"];
[archiver finishEncoding];
    
BOOL result = [mutableData writeToURL:[NSURL fileURLWithPath:strPath] atomically:YES];
    
if (result)
{
    NSLog(@"Success!!");
}


2. Decoding

NSArray* array = [[NSArray alloc] initWithArray:NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)];
NSString* strPath = [NSString stringWithFormat:@"%@/KeyedArchive", [array objectAtIndex:0]];
    
NSData* data = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:strPath]];
        
NSKeyedUnarchiver* archiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
NSString* str = [archiver decodeObjectForKey:@"Key"];
[archiver finishDecoding];
    
if (str)
{
    NSLog(@"Decoded Value : %@", str);
}
else
{
    NSLog(@"Failed!");
}