IOS --使用NSCoding歸檔和反歸檔


iOS開發中要想存儲對象可以使用NSCoding,要想存儲的對象必須實驗NSCoding協議

比如我們要存儲一個Student對象,那么Student類必須遵循NSCoding協議,然后實現NSCoding中得兩個方法。

@interface Student : NSObject <NSCoding>
  • 1

然后再.m文件中實現encodeWithCoder:(存)和initWithCoder:(讀)方法,這樣就告訴了程序這個對象應該怎么存,要存那些屬性,以及需要怎么讀!

/** * 將某個對象寫入文件時會調用 * 在這個方法中說清楚哪些屬性需要存儲 */ - (void)encodeWithCoder:(NSCoder *)encoder { [encoder encodeObject:self.no forKey:@"no"]; [encoder encodeInt:self.age forKey:@"age"]; [encoder encodeDouble:self.height forKey:@"height"]; }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
/** * 從文件中解析對象時會調用 * 在這個方法中說清楚哪些屬性需要存儲 */ - (id)initWithCoder:(NSCoder *)decoder { if (self = [super init]) { // 讀取文件的內容 self.no = [decoder decodeObjectForKey:@"no"]; self.age = [decoder decodeIntForKey:@"age"]; self.height = [decoder decodeDoubleForKey:@"height"]; } return self; }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

控制器中得讀寫方法。

- (IBAction)save { // 1.新的模型對象 Student *stu = [[Student alloc] init]; stu.no = @"42343254"; stu.age = 20; stu.height = 1.55; // 2.歸檔模型對象 // 2.1.獲得Documents的全路徑 NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; // 2.2.獲得文件的全路徑 NSString *path = [doc stringByAppendingPathComponent:@"stu.data"]; // 2.3.將對象歸檔 [NSKeyedArchiver archiveRootObject:stu toFile:path]; }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

反歸檔(讀取)

- (IBAction)read { // 1.獲得Documents的全路徑 NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; // 2.獲得文件的全路徑 NSString *path = [doc stringByAppendingPathComponent:@"stu.data"]; // 3.從文件中讀取MJStudent對象 Student *stu = [NSKeyedUnarchiver unarchiveObjectWithFile:path]; }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM