-1

我有一个在线 plist(格式为http://example.com/people.plist)。我怎么能让 UITable 视图从 plist 而不是静态数组中提取名称?

<plist version="1.0">
<array>
<dict>
    <key>fname</key>
    <string>Scott</string>
    <key>sname</key>
    <string>Sherwood</string>
    <key>age</key>
    <string>30</string>
</dict>
<dict>
    <key>fname</key>
    <string>Janet</string>
    <key>sname</key>
    <string>Smith</string>
    <key>age</key>
    <string>26</string>
</dict>
<dict>
    <key>fname</key>
    <string>John</string>
    <key>sname</key>
    <string>Blogs</string>
    <key>age</key>
    <string>20</string>
</dict>
</array>
</plist>

这是我的viewDidLoad

- (void)viewDidLoad
{
[super viewDidLoad];


Person *p1 = [[Person alloc] initWithFname:@"Scott" sname:@"Sherwood"  age:30];
Person *p2 = [[Person alloc] initWithFname:@"Janet" sname:@"Smith"  age:26];
Person *p3 = [[Person alloc] initWithFname:@"John" sname:@"Blogs"  age:20];

self.people = [NSArray arrayWithObjects:p1,p2,p3, nil];
}

这是我的tableView cellForRowAtIndexPath

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

// Configure the cell...
Person *p1 = [self.people objectAtIndex:indexPath.row];

cell.textLabel.text = p1.fname;
return cell;
}
4

1 回答 1

2

您可以为您的Person类创建一个自定义初始化程序,并几乎直接从 plist 填充数组:

@implementation Person

- (id)initWithDictionary:(NSDictionary *)dict
{
    NSString *fname = [dict objectForKey:@"fname"];
    NSString *sname = [dict objectForKey:@"sname"];
    NSString *age =   [dict objectForKey:@"age"  ];
    return self = [self initWithFname:fname sname:sname age:[age intValue]];
}

@end

然后做这样的事情:

NSString *path = [[NSBundle mainBundle] pathForResource:@"people" ofType:@"plist"];
NSArray *plist = [NSArray arrayWithContentsOfFile:path];

NSMutableArray *people = [NSMutableArray array];
for (NSDictionary *item in plist) {
    Person *p = [[Person alloc] initWithDictionary:item];
    [people addObject:p];
    [p release];
}

然后只是people用作数据源。

一个边际概念改进:不是将年龄存储为<string>,而是将其存储为<integer>。在这种情况下,您将拥有NSNumber对象(您也可以intValue在第一步中调用该方法)。

于 2013-03-10T13:57:47.530 回答