iPhone dev - 将一个对象数组写入/读取到文件中

时间:2011-07-28 12:32:36

标签: iphone objective-c serialization

我有一个名为listOfContactsToLay的数组 - 它包含带有3个字符串字段的Contact对象。如何将此数组成功写入文件? 这就是我所拥有的:

-(NSString*)fPath
{
    return [DocumentsDirectory() stringByAppendingPathComponent:@"quickdial.xml"];
}

//SERIALIZATION
- (void) save:(NSMutableArray*)array
{

   [NSKeyedArchiver archiveRootObject:array toFile:[self fPath]]; 

    NSLog(@"List of contacts been written in file");

}

// get that array back
- (NSMutableArray*)load
{
    NSLog(@"List of contacts is being read from file");
    return [NSKeyedUnarchiver unarchiveObjectWithFile:[self fPath]];

}

当然以下情况不起作用:

-(IBAction)doneWithContacts {
    [ContactManager createXmlInMydocumentsDirectory];
[self save:listOfContactsToLay];
    NSLog(@"List of contacts to lay saved!");
    [self.parentViewController dismissModalViewControllerAnimated:YES];

}

它会抛出无效的参数异常。

我该怎么办?如何序列化我的对象的MSMutableArray? 感谢

3 个答案:

答案 0 :(得分:1)

您的Contact类是否符合NSCoding协议。

More info

答案 1 :(得分:1)

答案 2 :(得分:0)

你关心文件的格式吗?如果没有,为什么不使用NSArray类的内置方法?

+ (id)arrayWithContentsOfFile:(NSString *)aPath;
- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag;

请参阅NSArray Class Reference