Objective-C資料儲存和讀取

來源:互聯網
上載者:User

標籤: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資料儲存和讀取

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.