将数组保存到包含自定义对象iPhone的Plist文件 [英] Saving Array to Plist file that contains Custom Objects iPhone

查看:222
本文介绍了将数组保存到包含自定义对象iPhone的Plist文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为XYZ的类继承自NSObject和一个包含XYZ对象的数组。我需要将这个数组写到一个plist文件到文档目录。在尝试[array writeToFile ....]之后,我发现writeToFile失败,因为数组包含XYZ类的自定义对象。



可能的解决方案是将对象转换为NSData。有什么不同的方法来实现这个?我发现 NSCoding 是适合的,但无法理解如何使用它。任何帮助将非常感激。

解决方案

p>只需要在对象中实现* - (void)encodeWithCoder:(NSCoder )encode 和* - (id)initWithCoder:(NSCoder )解码器其遵循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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆