Save array of objects with properties to plist

隐身守侯 提交于 2019-12-04 08:59:12
Anoop Vaidya

When you write a string or any primitive data to plist it can be saved directly. But when you try to save an object, you need to use NSCoding.

You have to implement two methods encodeWithCoder: to write and initWithCoder: to read it back in your BugData Class.

EDIT:

Something like this : Change Float to Integer or String or Array as per your requirement and give a suitable key to them.

- (void)encodeWithCoder:(NSCoder *)coder {
    [coder encodeObject:_title forKey:@"title"];
    [coder encodeFloat:_rating forKey:@"rating"];
    NSData *image = UIImagePNGRepresentation(_thumbImage);
    [coder encodeObject:(image) forKey:@"thumbImage"];
}


- (id)initWithCoder:(NSCoder *)coder {
    _title = [coder decodeObjectForKey:@"title"];
    _rating = [coder decodeFloatForKey:@"rating"];
    NSData *image = [coder decodeObjectForKey:@"thumbImage"];
    _thumbImage = [UIImage imageWithData:image];
    return self;
}

Even this will help you.

Implement NSCoding in your BugData class as below

- (void)encodeWithCoder:(NSCoder *)coder {
    [coder encodeFloat:title forKey:@"title"];
    [coder encodeFloat:rank forKey:@"rank"];
    [coder encodeObject:UIImagePNGRepresentation(thumbImage) forKey:@"thumbImageData"];
}




- (id)initWithCoder:(NSCoder *)coder {
    title = [coder decodeFloatForKey:@"title"];
    rank = [coder decodeFloatForKey:@"rank"];
    NSData *imgData = [coder decodeObjectForKey:@"thumbImageData"];
    thumbImage = [UIImage imageWithData:imgData ];
    return self;
}

BugData must implement the NSCoding protocol.You need this method to encode the data:

- (void) encodeWithCoder: (NSCoder*) encoder;

Where you should provide a NSData object representing the class (decode it with the decoder).
To read the plist you need to implement this method:

-(id) initWithCoder: (NSCoder*) decoder;

Where you read data from decoder and return a BugData object.

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