将数组保存到包含自定义对象iPhone的Plist文件 [英] Saving Array to Plist file that contains Custom Objects iPhone
问题描述
我有一个名为XYZ的类继承自NSObject和一个包含XYZ对象的数组。我需要将这个数组写到一个plist文件到文档目录。在尝试[array writeToFile ....]之后,我发现writeToFile失败,因为数组包含XYZ类的自定义对象。
可能的解决方案是将对象转换为NSData。有什么不同的方法来实现这个?我发现 NSCoding 是适合的,但无法理解如何使用它。任何帮助将非常感激。
// Header
@interface AnObject:NSObject< NSCoding>
//实现
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:ivar1 forKey:@ivar1];
[encoder encodeFloat:ivar2 forKey:@ivar2];
}
- (id)initWithCoder:(NSCoder *)decoder {
self = [super initWithCoder:coder];
ivar1 = [[coder decodeObjectForKey:@ivar1] retain];
ivar2 = [[coder decodeObjectForKey:@ivar2] retain];
return self;
}
您也可以查看官方文档在这里。
I have a class called XYZ inheriting from NSObject and an array which contains objects of XYZ. I need to write this array to a plist file on to documents directory. After trying [array writeToFile....], I found that writeToFile fails because the array contains custom objects of XYZ class.
The possible solution to this is to convert the objects to NSData. What are the different ways of achieving this?? I found that NSCoding is suitable but cant understand how to use it. Any help will be greatly appreciated.
There is a very good tutorial on the Ray Wenderlich's blog which explains how to work with the NSCoding.
Simply you just have to implement the *-(void)encodeWithCoder:(NSCoder )encode and *-(id)initWithCoder:(NSCoder )decoder methods in your object that respects the NSCoding protocol like that:
// Header
@interface AnObject: NSObject <NSCoding>
// Implementation
- (void) encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:ivar1 forKey:@"ivar1"];
[encoder encodeFloat:ivar2 forKey:@"ivar2"];
}
- (id)initWithCoder:(NSCoder *)decoder {
self = [super initWithCoder:coder];
ivar1 = [[coder decodeObjectForKey:@"ivar1"] retain];
ivar2 = [[coder decodeObjectForKey:@"ivar2"] retain];
return self;
}
You can also check the official documentation here.
这篇关于将数组保存到包含自定义对象iPhone的Plist文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!