Mohd Shahid
Mohd Shahid

Reputation: 1606

how to show image name from NSArray of UIImage in iOS

I have an array of images, I just want to get the image name from the array e.g.

countryArray = [[NSMutableArray arrayWithObjects:
[UIImage imageNamed:@"india.png"],
[UIImage imageNamed:@"australia.png"],
[UIImage imageNamed:@"singapore.png"],
[UIImage imageNamed:@"america.png"],
nil] retain];


NSLog(@"image name at row %d is '%@'.",1,[countryArray objectAtIndex:1]);

It should show australia.png, instead it shows:

image name at row 1 is UIImage: 0x4b14910

Upvotes: 2

Views: 6933

Answers (1)

PengOne
PengOne

Reputation: 48398

A UIImage doesn't remember its filename once the image is loaded, so there is no direct way to achieve this with a property, e.g. myImage.name.

One option is to use a separate NSMutableArray to store the names as strings. For instance

countryStringArray = [[NSMutableArray arrayWithObjects:
@"india",
@"australia",
@"singapore",
@"america",
nil] retain];

countryImageArray = [[NSMutableArray arrayWithObjects:
[UIImage imageNamed:[countryStringArray objectAtIndex:0]],
[UIImage imageNamed:[countryStringArray objectAtIndex:1]],
[UIImage imageNamed:[countryStringArray objectAtIndex:2]],
[UIImage imageNamed:[countryStringArray objectAtIndex:3]],
nil] retain];

You could even make use of a for loop to populate the countryImageArray.

A second option is to use an NSMutableDictionary. This is essentially the same thing, in fact you can achieve it by

countryDictionary = [NSDictionary dictionaryWithObjects:countryImageArray forKeys:countryStringArray];

but it has some advantages in terms of cleanness of retrieving a specific country image by name. The direct way to define it is

[countryDictionary setObject:[UIImage imageNamed:@"india.png"] forKey:@"india"];
[countryDictionary setObject:[UIImage imageNamed:@"australia.png"] forKey:@"australia"];
[countryDictionary setObject:[UIImage imageNamed:@"singapore.png"] forKey:@"singapore"];
[countryDictionary setObject:[UIImage imageNamed:@"america.png"] forKey:@"america"];

Upvotes: 4

Related Questions