我知道它很愚蠢,但是如何将此数组重新创建为plist列表
candyArray = [NSArray arrayWithObjects:
[Candy candyOfCategory:@"chocolate" name:@"chocolate bar"],
[Candy candyOfCategory:@"chocolate" name:@"chocolate chip"],
[Candy candyOfCategory:@"chocolate" name:@"dark chocolate"],
[Candy candyOfCategory:@"hard" name:@"lollipop"],
[Candy candyOfCategory:@"hard" name:@"candy cane"],
[Candy candyOfCategory:@"hard" name:@"jaw breaker"],
[Candy candyOfCategory:@"other" name:@"caramel"],
[Candy candyOfCategory:@"other" name:@"sour chew"],
[Candy candyOfCategory:@"other" name:@"peanut butter cup"],
[Candy candyOfCategory:@"other" name:@"gummi bear"], nil];
感谢任何人的帮助!
尝试这样做,但在此之前包括您的数组,然后按照以下内容操作:-
NSFileManager *fileManager =[NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask,YES);
NSString *desktopDirectory = [paths objectAtIndex:0];
NSString *path = [desktopDirectory stringByAppendingPathComponent:@"yourfile.plist"];
NSMutableDictionary *mut=[NSMutableDictionary dictionary];
[mut setObject:candyArray forKey:@"yourKey"];
If ([mut writeToFile:path automatically:YES])
{
NSLog(@"file created");
}
Andy,
侯赛因的答案很接近,但在存档自定义类型时会失败。
简单的答案。您必须采用 NSCoding 协议,因为您使用自定义类 (Candy)。实现以下任务initWithCoder,encodeWithCoder和默认存档器将负责其余的工作。如果您想以其他格式(二进制等)存档,请参考NSData和NSCoder(NSKeyedArchiver)。JSON也是另一个很好的精益选择。
如果这太麻烦了,请放弃自定义对象并将基元嵌套在数组或字典中。对于复杂的自定义类型,不鼓励这样做,并且会构建技术债务,但对于简单的结构,鼓励这样做。想分享苹果的最佳实践。
支持的 plist 类型 (iOS)
NSString,NSNumber,NSDate,NSData,美国国家安全局,国家词典
简单示例(NSArray,NSDictionary)https://developer.apple.com/library/mac/documentation/cocoa/Conceptual/Archiving/Articles/serializing.html#//apple_ref/doc/uid/20000952-BABBEJEE
自定义对象的完整参考文档 (NSCoding)https://developer.apple.com/library/mac/documentation/cocoa/Conceptual/Archiving/Archiving.html#//apple_ref/doc/uid/10000047i