Given a .plist similar to :
<plist version="1.0">
<array>
<dict>
<key>name</key>
<string>Afghanistan</string>
<key>government</key>
<string>Islamic Republic</string>
<key>population</key>
<integer>0</integer>
<key>image</key>
<string>/Flags/afghanistan.png</string>
</dict>
<dict>
<key>name</key>
<string>Albania</string>
<key>government</key>
<string>Emerging Democracy</string>
<key>population</key>
<integer>0</integer>
<key>image</key>
<string>/Flags/albania.png</string>
</dict>
.... etc.
And ViewController.m :
#import "FirstViewController.h"
@implementation FirstViewController
@synthesize sortedCountries;
-(void)viewDidLoad {
NSString *path = [[NSBundle mainBundle] pathForResource:@"countries" ofType:@"plist"];
NSArray *countries = [NSArray arrayWithContentsOfFile:path];
NSSortDescriptor *descriptor = [[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES] autorelease];
self.sortedCountries = [countries sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]];
}
-(UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *country = [sortedCountries objectAtIndex:indexPath.row];
NSString *countryName = [country objectForKey:@"name"];
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell =
[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier] autorelease];
}
NSDictionary *item = (NSDictionary *)[sortedCountries objectAtIndex:indexPath.row];
NSString *path = [[NSBundle mainBundle] pathForResource:[item objectForKey:@"image"] ofType:@"png"];
UIImage *theImage = [UIImage imageWithContentsOfFile:path];
cell.imageView.image = theImage;
cell.textLabel.text = countryName;
return cell;
}
This puts countryName in ascending alphabetical order as expeted in the UITableView Cells. What is not working is cell.imageView.image.
It puts afghanistan.png in the first UITableViewCell as expected. The Cells that follow also receive afghanistan.png as well however. ( The second cell should receive ‘albania.png’, etc ). How can I fix this UIImageView problem?
Use
imageNamedinstead.