Write custom object to .plist in Cocoa

◇◆丶佛笑我妖孽 提交于 2019-11-27 22:34:01

Property list files can only store basic data types and cannot contain custom objects. You need to convert your object to an NSData object if you want it to be written to the plist. You can do this with NSKeyedArchiver, which will encode an object which conforms to the NSCoding protocol into an NSData object.

DownloadObject *object = [[DownloadObject alloc]initWithKey:number name:@"hey" progress:number size:number path:@"hey" progressBytes:number];
NSData* objData = [NSKeyedArchiver archivedDataWithRootObject:object];
[downloadArray addObject:objData];
[object release];

When you want to reconstruct your object from the NSData object, you use NSKeyedUnarchiver:

NSData* objData = [downloadArray objectAtIndex:0];
DownloadObject* object = [NSKeyedUnarchiver unarchiveObjectWithData:objData];

You also have several memory leaks in your code. In your -initWithCoder: method, you should not be using accessors to set the value of the ivars, you should just set the ivars directly, like so:

key = [[coder decodeObjectForKey:@"Key"] copy];

You are calling -retain and then using the accessor which is specified as copy, which will mean your object has a retain count of 2 and will not be released. In general you should avoid using accessors in init methods.

Also, in the code where you allocate your downloadArray object, you are calling -alloc and then -retain on the object, which will leave it with a retainCount of 2. You should re-read the Objective-C Memory Management Guidelines.

This works for me:

NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];

[archiver encodeObject:highScoreArray forKey:kHighScoreArrayKey];

[archiver finishEncoding];

[data writeToFile:[self dataFilePath] atomically:YES];

[data release];
[archiver release];
BOOL flag = false;

    ObjectFileClass  *obj = [yourMutableArray objectAtIndex:0];

   //TO Write Data . . .

    NSData* archiveData = [NSKeyedArchiver archivedDataWithRootObject:obj.title];
    flag =[archiveData writeToFile:path options:NSDataWritingAtomic error:&error];
}


if (flag) {
    NSLog(@"Written");

  //To Read Data . . .

    NSData *archiveData = [NSData dataWithContentsOfFile:path];
    id yourClassInstance = [NSKeyedUnarchiver unarchiveObjectWithData:archiveData]; // choose the type of your class instance  . . .
    NSLog(@"%@",yourClassInstance);
}else{

    NSLog(@"Not Written");
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!