如何从这些数组创建 plist 文件?
Posted
技术标签:
【中文标题】如何从这些数组创建 plist 文件?【英文标题】:How can i create a plist file from these arrays? 【发布时间】:2016-08-31 20:30:48 【问题描述】:我有一个 NSCollectionView 可以像这样读取数据:
self.contents = @[
@@"itemTitle":@"Product 1",
@"itemPrice":@"$20.90",
@"itemImage":@"PastedGraphic-1.png",
@@"itemTitle":@"Product 2",
@"itemPrice":@"$10.90",
@"itemImage":@"PastedGraphic-3.png",
@@"itemTitle":@"Product 3",
@"itemPrice":@"$9810.90",
@"itemImage":@"PastedGraphic-4.png",
@@"itemTitle":@"Product 4",
@"itemPrice":@"$100.90",
@"itemImage":@"PastedGraphic-5.png",
@@"itemTitle":@"Product 5",
@"itemPrice":@"$109.19",
@"itemImage":@"PastedGraphic-1.png",
@@"itemTitle":@"Product 6",
@"itemPrice":@"$910.90",
@"itemImage":@"PastedGraphic-6.png",
@@"itemTitle":@"Product 7",
@"itemPrice":@"$632.90",
@"itemImage":@"PastedGraphic-7.png",
];
我的问题是,我怎样才能把这段代码变成一个plist文件,这样我就可以使用这段代码把plist文件的数据放到NSCollectionView中:
NSString* plistPath = [[NSBundle mainBundle] pathForResource:@"legue" ofType:@"plist"];
self.contents = [[NSArray alloc] initWithContentsOfFile:plistPath];
【问题讨论】:
既然已经这样写了,你可以在Desktop中使用writeToFile:
(例如)来创建一个plist文件,然后使用它。
【参考方案1】:
NSString *filename = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
// your plist path
NSString *path = [filename stringByAppendingPathComponent:@"legue.plist"];
[contents writeToFile:path atomically:YES];
// test it
NSString *str = [[NSBundle mainBundle]pathForResource:@"legue.plist" ofType:nil];
NSLog(@"%@",str); // str = nil;
所以你应该创建一个新的plist文件,然后你可以使用[NSBundle mainBundle]。
【讨论】:
【参考方案2】:您可以使用以下函数(objective-C)来创建plist文件:
+ (void) writeToPlist
NSArray* contents = @[
@@"itemTitle":@"Product 1",
@"itemPrice":@"$20.90",
@"itemImage":@"PastedGraphic-1.png",
@@"itemTitle":@"Product 2",
@"itemPrice":@"$10.90",
@"itemImage":@"PastedGraphic-3.png",
@@"itemTitle":@"Product 3",
@"itemPrice":@"$9810.90",
@"itemImage":@"PastedGraphic-4.png",
@@"itemTitle":@"Product 4",
@"itemPrice":@"$100.90",
@"itemImage":@"PastedGraphic-5.png",
@@"itemTitle":@"Product 5",
@"itemPrice":@"$109.19",
@"itemImage":@"PastedGraphic-1.png",
@@"itemTitle":@"Product 6",
@"itemPrice":@"$910.90",
@"itemImage":@"PastedGraphic-6.png",
@@"itemTitle":@"Product 7",
@"itemPrice":@"$632.90",
@"itemImage":@"PastedGraphic-7.png",
];
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectoryPath
stringByAppendingPathComponent:@"legue.plist"];
[contents writeToFile:filePath atomically: YES];
【讨论】:
【参考方案3】:您可以创建一个新的 plist 文件并设计您的 plist 如下图:
【讨论】:
以上是关于如何从这些数组创建 plist 文件?的主要内容,如果未能解决你的问题,请参考以下文章
如何在 iPhone 中以编程方式在 plist 文件中添加多个数组