-1

オンライン( http://example.com/people.plistの形式)に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];
}

これが私のtableViewcellForRowAtIndexPathです

- (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、データソースとして使用します。

1つのわずかな概念の改善:年齢をとして保存する代わりに、として保存<string><integer>ます。この場合、NSNumberオブジェクトがあります(最初のステップでメソッドを呼び出すこともできますintValue)。

于 2013-03-10T13:57:47.530 に答える