Mario Mario - 4 months ago 23
Objective-C Question

how to display values on labels from plist. objective-c

i have the plist:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
<dict>
<key>name</key>
<string>Daniel</string>
<key>Description</key>
<string>Bad boy</string>
</dict>
<dict>
<key>name</key>
<string>Mary</string>
<key>description</key>
<string>Good girl</string>
</dict>
</array>
</plist>


i want to display on my label's values name and description depending of name:

NSString *path = [[NSBundle mainBundle] pathForResource:@"PropList" ofType:@"plist"];
ComplexArray = [NSArray arrayWithContentsOfFile:path];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
for (int i = 0; i < [ComplexArray count]; i++) {
ThirdViewController *item = [ComplexArray objectAtIndex:i];

if ([item.name isEqualToString: @"Mary"]) {
_nameLabel.text = [dict objectForKey:@"name"];
_descriptionLabel.text = [dict objectForKey:@"description"];
}
}


And why i can't do like this (i did this when i have no plist, but now this return errors):

NSString *path = [[NSBundle mainBundle] pathForResource:@"PropList" ofType:@"plist"];
ComplexArray = [NSArray arrayWithContentsOfFile:path];
for (int i = 0; i < [ComplexArray count]; i++) {
ThirdViewController *item = [ComplexArray objectAtIndex:i];
if ([item.name isEqualToString: @"Mary"]) {
_nameLabel.text=item.name;
_descriptionLabel.text=item.description;
}
}

Answer

Again, you pretty much had it right already.

NSString *path = [[NSBundle mainBundle] pathForResource:@"PropList" ofType:@"plist"];
ComplexArray = [NSArray arrayWithContentsOfFile:path];
for (NSDictionary *dict in ComplexArray) {
    if ([dict[@"name"] isEqualToString:@"Mary"]) {
        _nameLabel.text = dict[@"name"];
        _descriptionLabel.text = dict[@"description"];
        break;
    }  
}