保存对象的数组属性的plist [英] Save array of objects with properties to plist
问题描述
我有一个包含不同的对象,如字符串,UIImage的,等一个可变数组
它们的排序是这样的:
I have a Mutable Array containing different objects such as strings, UIImage , etc. They are sorted like this:
例如:
BugData *bug1 = [[BugData alloc]initWithTitle:@"Spider" rank:@"123" thumbImage:[UIImage imageNamed:@"1.jpeg"]];
...
...
NSMutableArray *bugs = [NSMutableArray arrayWithObjects:bug1,bug2,bug3,bug4, nil];
所以基本上它是具有不同属性的对象的数组。
So basically it's an array with objects with different properties.
我想一个字符串保存到下一个code文件,它的工作很好,但是当我尝试保存的对象数组,我得到一个空的plist文件。
I Tried to save a single string to a file with the next code and it's working fine but when I try to save the array with the objects, i get an empty plist file.
NSString *docsDir = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString * path = [docsDir stringByAppendingPathComponent:@"data.plist"];
NSLog(@"%@",bugs); //Making sure the array is full
[bugs writeToFile:path atomically:YES];
我在做什么错了?
What am I doing wrong?
推荐答案
当你写一个字符串或任何原始数据的plist可以直接保存。但是,当您尝试保存一个对象,你需要使用NSCoding。
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.
您必须实现两个方法连接codeWith codeR:
来写 initWith codeR:
来读它放回你的BugData类。
You have to implement two methods encodeWithCoder:
to write and initWithCoder:
to read it back in your BugData Class.
编辑:
事情是这样的:
更改浮点数到整数或字符串数组或者按照您的要求,并给予合适的钥匙给他们。
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;
}
这篇关于保存对象的数组属性的plist的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!