将arraywithobjects重新创建为plist

时间:2013-10-22 15:21:27

标签: iphone ios objective-c sdk nsarray

我知道它的愚蠢,但我如何将这个数组重新创建到一个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];

感谢任何人的帮助!

2 个答案:

答案 0 :(得分:0)

尝试这样但在此之前包括您的阵列,然后按照以下说明: -

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");
        }

答案 1 :(得分:0)

安迪,

Hussain的答案很接近,但归档自定义类型时会失败。

简单的回答。您必须采用NSCoding协议,因为您使用的是自定义类(Candy)。实现以下任务initWithCoder,encodeWithCoder,默认的归档器将处理其余的任务。如果您想以其他格式存档(二进制等),请参考NSData和NSCoder(NSKeyedArchiver)。 JSON也是另一个很好的精益选择。

如果在数组或词典中使用自定义对象和嵌套基元太麻烦了。对于复杂的自定义类型,这是不鼓励的,并且将建立技术债务,但鼓励简单的结构。想要分享Apple最佳实践。

支持的plist类型(iOS)

的NSString, 的NSNumber, NSDate的, NSData的, NSArray的, 的NSDictionary

简单示例(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