NSString *homePath = NSHomeDirectory(); NSString *filePath = [homePath stringByAppendingPathComponent:@"array.archiver"]; NSMutableData *mutableData = [NSMutableData data]; NSKeyedArchiver *archive = [[NSKeyedArchiver alloc] initForWritingWithMutableData:mutableData]; [archive encodeObject:@"jack" forKey:@"name"]; [archive encodeInt:21 forKey:@"age"]; [archive finishEncoding]; [mutableData writeToFile:filePath atomically:YES]; //------解归档------ NSData *contentData = [NSData dataWithContentsOfFile:filePath]; NSKeyedUnarchiver *unchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:contentData]; NSString *nameString = [unchiver decodeObjectForKey:@"name"]; int age = [unchiver decodeIntForKey:@"age"]; NSLog(@"nameString : %@",nameString); NSLog(@"age : %d",age);
序列化与反序列化的对象必须支持NSCoding协议,自定义的对象需要自己实现NSCoding协议