使用 Xcode 读取和编写具有字典数组的 Plist
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6729044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read & write my Plist that has an Array of Dictionary using Xcode
提问by AlwynIsPat
here's my issue, i'm trying to create a UITableView that is able to display the Names in my plist into the cells. I can't get the names out of the Plist. guess i'm not very certain with the programming codes required to extract the info.
这是我的问题,我正在尝试创建一个 UITableView,它能够将我的 plist 中的名称显示到单元格中。我无法从 Plist 中获取名称。我猜我对提取信息所需的编程代码不是很确定。
if you could help by providing a good tutorial or sample codes would be wonderful. Thanks!
如果您能提供一个很好的教程或示例代码来提供帮助,那就太好了。谢谢!
<array>
<dict>
<key>Name</key>
<string>Device 2</string>
</dict>
<dict>
<key>Name</key>
<string>Device 1</string>
</dict>
</array>
These codes are in my viewDidLoad..
这些代码在我的 viewDidLoad 中。
NSBundle *bundle = [NSBundle mainBundle];
NSString *path = [bundle pathForResource:@"devicelist" ofType:@"plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:path]) {
NSLog(@"The file exists");
} else {
NSLog(@"The file does not exist");
}
contentDict = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
NSLog(@"The count: %i", [contentDict count]);
contentArray = [NSMutableArray arrayWithContentsOfFile:path];
NSLog(@"The array: %i", [contentArray count]);
[contentArray retain];
[contentDict retain];
[mainTableView reloadData];
and these in my tableView..
而这些在我的 tableView..
static NSString *MyIdentifier = @"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier]autorelease];
}
cell.textLabel.text = [sortedArray objectForKey:indexPath.row];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
回答by indiantroy
Maybe you wanna try out the below in viewDidLoad:
也许您想在 viewDidLoad 中尝试以下内容:
NSBundle *bundle = [NSBundle mainBundle];
NSString *path = [bundle pathForResource:@"devicelist" ofType:@"plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:path]) {
NSLog(@"The file exists");
self.contentArray = [NSMutableArray arrayWithContentsOfFile:path];
NSLog(@"The array: %i", [contentArray count]);
[mainTableView reloadData];
}
just notice that contentArray should be a retain property and then in cellForRowAtIndexPath method:
请注意 contentArray 应该是一个保留属性,然后在 cellForRowAtIndexPath 方法中:
NSDictionary *dict = [self.contentArray objectAtIndex:indexPath.row];
cell.textLabel.text = (NSString*)[dict objectForKey:@"Name"];
Hope this helps...
希望这可以帮助...