Reputation: 6614
When setting the image for a button, I use stringWithFormat:
like so:
[buttonImage setImage:[ImgUtil image:[NSString stringWithFormat:@"myImage_%d.png", selectNum + 1 ]] ];
I want to inspect that string. I thought maybe I could get the name back from the button:
if (buttonImage.image == [UIImage imageNamed:@"myImage_2.png"]) {
NSLog(@"the name of the buttonImage is %@", buttonImage.image);
}
but that doesn't work. How can I look at that string?
Upvotes: 0
Views: 214
Reputation: 4373
No, you can't.
buttonImage.image
is a UIImage stored in memory inside the button.
[UIImage imageNamed:@"myImage_2.png"]
creates an entirely different UIImage. Both UIImages could very well have been created from the same file--in this case, @"myImage_2.png"
--but they are two separate UIImages in memory.
The ==
check in your line:
if(buttonImage.image == [UIImage imageNamed:@"myImage_2.png"])
Does not check if the UIImages were created from the same file; it checks if they are pointing to the same location in memory. Which they are not, because they are two separately created and stored UIImage instances.
--
So, no--you cannot do this. Something that might solve your problem another way, though, is to subclass UIButton and add a properly NSString* imageFilename
. (If you're setting different images for each control state, you'd need more than one variable to store those image file names in). Then override the setImage:forControlState
method of the UIButton subclass and store the filename there every time the image is changed. Then you can perform the following check:
if([imageFileName isEqualToString:[[NSString stringWithFormat:@"myImage_%d.png", selectNum + 1 ]])
And that would get you the answer you want!
Upvotes: 2
Reputation: 2027
If what you want is to "test what the "myImage_%d.png" ends up being" in the following line:
[buttonImage setImage:[ImgUtil image:[NSString stringWithFormat:@"myImage_%d.png", selectNum + 1 ]] ];
Then I would suggest that you reformat and simplify your code. It will give you the additional advantage of making it easier to read:
NSString* imageName = [NSString stringWithFormat:@"myImage_%d.png", selectNum + 1 ];
NSLog(@"imageName is %@", imageName);
[buttonImage setImage:[ImgUtil image:imageName]];
Upvotes: 2
Reputation: 662
selectNum stands for the selected image, right?If so, try to get selectNum when picking the picture.
Upvotes: 0
Reputation: 8907
You could use associated references to attach a string the key "name" at load time. You create the UIImage from a file, and attach the name using the objective-c associated references API: here.
You can also sub-class UIImage to store an extra name.
You can even add a category to provide an easy API.
Upvotes: 3
Reputation: 56809
You can store the UIImage as instance of the class, and compare it. You won't be using more memory than a pointer.
Upvotes: 1