標籤:box represent one 變數 nsstring blog default repr library
一、NSCoding協議中的Archiving和Unarchiving
(1)Archiving一個object,會記錄這個對象的所有的properties到filesystem;
(2)Unarchiving一個object,會從data中重新建立這個object。
類中的實力要Archiving和Unarchiving,需遵守NSCoding協議,並要實現以下兩個方法:
@protocol NSCoding-(void)encodeWithCoder:(NSCoder*)aCoder;-(instancetype)initWithCoder:(NSCoder*)aCoder;@end
例:
//存-(void)encodeWithCoder:(NSCoder*)aCoder{ [aCoder encodeObject:self.itemName forKey:@"itemName"]; [aCoder encodeInt:self.valueInDollars forKey:@"valueInDollars"];}//取-(instancetype)initWithCoder:(NSCoder*)aCoder{ self = [super init]; if(self){ _itemName = [aDecoder decodeObjectForKey:@"itemName"]; _valueInDollars = [aDecoder decodeIntForKey:@"valueInDollars"]; } return self; }
類似地,
XIB file被儲存,即是把views archived into XIB file;
當應用程式啟動時,從XIB file裡unarchive the views。
二、使用NSCoder的子類在sandbox中存取
應用程式的sandbox是一個目錄,包括:Documents、Library(不會在應用程式退出時刪除)、tmp(會在應用程式退出時刪除)。
NSCoder的子類,這裡指:NSKeyedArchiver和NSKeyedUnArchiver這兩個類。
例:
//產生file path-(NSString *)itemArchivePath { NSArray *documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES); NSString *documentDirectory = [documentDirectories firstObject]; return [ documentDirectory stringByAppendingPathComponent:@"items.archive"];}//存-(BOOL)saveChanges { NSString *path = [self itemArchivePath]; return [NSKeyedArchiver archiveRootObject:XXX toFile:path];}//取-(instancetype)initPrivate { self = [super init]; if(self){ NSString *path = [self itemArchivePath]; _privateItem = [NSKeyedUnarchiver unarchiveObjectWithFile:path]; } return self;}
NSKeyedArchiver存對象的過程分為兩步:(1)先調用encodeWithCoder來encode變數到NSKeyedArchiver;(2)再存到path。
三、用NSData寫入FileSystem
例:
-(NSString*)imagePathForKey:(NSString*)key{ NSArray *documentDirectories =....; NSString *documentDirectory = ...; return [ documentDirectory stringByAppendingPathComponent:key];}//寫入NSString imagePath = [self imagePathForKey:key];NSData *data = UIImageJPEGRepresentation(image,0.5);[data writeToFile:imagePath atomically:YES];//刪除[[NSFileManager defaultManager] removeItemAtPath:imagePath error:nil];//讀取UIImage *image = [UIImage imageWithContentOfFile:imagePath];
其中NSFileManager可以擷取、建立、拷貝以及移動檔案和目錄。
Objective-C資料儲存和讀取