我如何更改此静态数组以从xCode中的此plist中提取?

时间:2013-03-10 13:40:29

标签: ios objective-c arrays plist

我有一个在线定位的plist(格式为http://example.com/people.plist)。我怎么能让UITable View从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;
}

1 个答案:

答案 0 :(得分: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方法)。