Finding image name loaded into UIImage instance - objective-c

How can I find out what the image name (usually file name?) loaded into a UIImage instance is? In this case, they were all initWithContentsOfFile:.

Once it's loaded using that, you can't. The file name is only used to load the data into memory. After that, it becomes irrelevant.
If you need to maintain the file name, then perhaps you need to make a class with the filename (as an NSString or NSURL, perhaps) and the image data (as an NSImage or NSData object) as ivars. I'm not sure what your application is, so I can't give you any architectural advice at this point.

If you already know what the image names are you can compare your image to another image using image named:
if (bg.image == [UIImage imageNamed:#"field.jpeg"]) {
bg.image = [UIImage imageNamed:#"cave.jpeg"];
} else {
bg.image = [UIImage imageNamed:#"field.jpeg"];
}
Here I use one button to switch between two images.

It's also something you can't just add a category on UIImage to, unfortunately, because it requires state.

Related

Checking whether two objects being used in two arrays are the same

I have two arrays that include 5 pictures of a background with a solid color. This is the code used to put the images into the arrays:
self.colorArray = #[
[UIImage imageNamed:#"orange_square"],
[UIImage imageNamed:#"purple_square"],
[UIImage imageNamed:#"red_square"],
[UIImage imageNamed:#"blue_square"],
[UIImage imageNamed:#"green_square"],
];
self.iconColorArray = #[
[UIImage imageNamed:#"orange_icon"],
[UIImage imageNamed:#"purple_icon"],
[UIImage imageNamed:#"red_icon"],
[UIImage imageNamed:#"blue_icon"],
[UIImage imageNamed:#"green_icon"],
];
As you can see the images are respectively put in order in terms of the color of their background. (I use different images for the arrays because iconColorArray is being used for a smaller UIImageView)
The app randomly changes the images of the two UIImageViews.
What I want is a if-else statement to compare the two arrays to see if the same objectAtIndex is being used. Exp: If orange_square is used for one UIImageView and orange_icon is being used for the other, the condition in the if-else statement will return true.
Basically to answer my question, just tell me how I would get the index of an object being used by a UIImageView in a array.
Edit:
Using Matt's advice, I changed the code to:
NSUInteger d = [self.colorArray indexOfObject:self.squareOne.image];
NSUInteger e = [self.iconColorArray indexOfObject:self.icon.image];
Now, I can compare them.
The way you get the index of an object is with (wait for it) indexOfObject:.
The problem is that the use of this method presupposes that this object can be compared for equality. I don't know whether UIImage does; I rather doubt it, but you can try.
Another possibility is indexOfObjectIdenticalTo:; this might work if the image is not copied by the image view but is an actual reference to one and the same image as the image in the array.
Having said all that, which would I do? None of them. I wouldn't even keep arrays of images; it's terribly wasteful of memory, and your app is likely to crash before it gets off the ground. What I would do is keep an array of the names of the images; strings are tiny, images are huge. And in order to make the comparison, I would subclass UIImageView to have a name property so that I could assign the name as well as the image, and now the problem is trivial.
Or you could even display the images through a view controller of their own, and give the view controller the name property. As a matter of fact I happen to have an example of doing that:
https://github.com/mattneub/Programming-iOS-Book-Examples/blob/master/bk2ch06p311pageController/ch19p626pageController/Pep.swift
And in fact if you explore the rest of that project you will see that I the proceed to do exactly what you are asking to do: to learn what pep boy is being displayed, I ask the Pep object for its boy string and I look up its index in a list of Pep boys:
https://github.com/mattneub/Programming-iOS-Book-Examples/blob/master/bk2ch06p311pageController/ch19p626pageController/AppDelegate.swift
It's in Swift so I use find instead of indexOfObject: but it amounts to the same thing.
You could create a third object as a dictionary, where the image square names names are the keys are the keys. And then you colorArray and iconColorArray could derive from this dictionary.
self.imageMap = { #"orange_square" : #"orange_icon",
#"purple_square" : #"purple_icon" }
- (BOOL)squareUsed:(UIImage *)square isSameAsIcon:(UIImage *)iconUsed {
for (NSString *key in self.imageMap) {
if ([[UIImage imageNamed:key] isEqual:square]) {
if ([UIImage imageNamed:self.imageMap[key]] isEqual:iconUsed]) {
return YES;
}
// We matched the square and the icon didn't match.
return NO;
}
}
// We never matched the square. Assert?
return NO;
}

Objective-c convert a parent class to its derived class

I have a custom class named MyImage inherit from UIImage. Now I have a UIImage object, is there any ways to convert it into a MyImage object?
Update
Sorry for being unclear.
I cannot use a category because I need to add new properties to my class.
What I want to accomplish is to just let my MyImage object point to the original UIImage object.
Update 2
I tried something like this:
- (MyImage*)initWithUIImage:(UIImage *)image {
if (self = [super init]) {
self = image;
}
return self;
}
Obvious it does not work.
Also, since UIImage does not have a method named 'initWithImage:(UIImage*)', I cannot write something like
myImage = [[MyImage alloc] initWithImage:uiImage];
I also tried
self = [image copy]
But the return value is still a UIImage object, not a MyImage object.
Update 3
In MyImage, I need to add 3 properties: url, width, and height. Since I am writing a instant messaging app, and when receiving a new image message, I only have its url, width, and height. Then I assign those to a MyImage object, and download the image in the background.
Now given an original UIImage A, I want to create a new MyImage object B, which points to the same image as A, but with those new properties unassigned. Then I manually assign url, width, and height to B.
to #rmaddy, could you tell me how to write the method
[[MyImage alloc] initWithImage:(UIImage*)]
?
One way I can come up is first convert the UIImage object to NSData, then use
[MyImage imageWithData:]
Is there a better way?
I do not necessarily recommend this as a solution, but there is indeed a way to do exactly what you are looking for. It is called ISA Swizzling. Think of it like method swizzling but for Classes instead of methods.
Take a look at the Objective-C runtime's object_setClass [link]
I won't go into it (there are better resources out there), but this is essentially how KVO works. Regardless, it would be helpful if you better described the functionality of your UIImage subclass, so that we could help describe why a custom initializer as rmaddy describes is probably the best solution.
Your MyImage class is a subclass of UIImage, so if you're creating a new instance you need to properly initialize the superclass as well. UIImage doesn't provide a method to do that from another UIImage instance, but you can use a CGImage, and you can get one of those from the existing image. So do this:
- (MyImage*)initWithUIImage:(UIImage *)image {
if (self = [super initWithCGImage:image.CGImage]) {
// put any necessary MyImage-specific stuff here
}
return self;
}

How to override a method in framework's class (runtime)

problem:
framework will cache the image data when above:
[UIImage imageNamed:]
I don't want the caching happen,so I can replace it by
[UIImage imageOfContentOfFile:]
Seems solved,but after my tests,in xib's instantiate progress, framework uses imageNamed: rather than imageOfContentOfFile.
That is, images loaded by xib still cached.
So I try to override the UIImage's imageNamed: method, make all this method DO NOT CACHE.
--try1. category:
#implementation UIImage (ImageNamedNoCache)
+ (UIImage *)imageNamed:(NSString *)name;
{
NSString* path = [[NSBundle mainBundle] pathForResource:name ofType:nil];
return [UIImage imageWithContentsOfFile:path];
}
#end
--result:warning."Category is implementing a method which will also be implemented by its primary class"
--try2. runtime replace the method's imp
//get super method
Method method_imageNamed = class_getClassMethod([UIImage class], #selector(imageNamed:));
//get my method
Method method_myImageNamed = class_getClassMethod([self class], #selector(myImageNamed:));
//get my imp
IMP imp_myImageNamed = method_getImplementation(method_myImageNamed);
//set super method's imp to my imp
method_setImplementation(method_imageNamed, imp_myImageNamed);
--result
these too try only work when I invoke [UIImage imageNamed:]
but xib's instantiation doesn't work.
help me, thanks
Sounds like a job for method swizzling. I find it dangerous and unnecessary, but if you are so inclined, it is an option. Use at your own risk.
The category method should be fine, just give your method a different name. It's my understanding that it's not good practice to override methods in a category, but adding a new one is fine.
Correct me if I do not interpret correctly, but it looks like your core problem is that you are trying to get framework (i.e., Apple code) to call imageWithContentsOfFile instead of imageNamed when loading xibs.
A third option might be to leave the UIImageViews in the xib 'blank' as a placeholder, and then programmatically loading UIImages into them later (for example in the FileOwner's init code), perhaps with the help of the 'tag' property + a dictionary to determine the right image, if it's convenient. Or you could even create both the images and their views dynamically instead of keeping them in the xib file. Obviously there are lots of tradeoffs here.
Your solution isn't good :) Caching is used for good reasons.
Just don't use [UIImage imageNamed:] In YOUR code, and all will be fine
If you Actually need not to cache your images, you should use method #2.
NOTE: Images(actually, all objects) from XIBS are being loaded with -[object initWithCoder:], and not with [UIImage imageNamed:] or [UIImage imageWithContentsOfFile:]

Is it necessary to use a temporary variable when setting a properties' value?

I have a (retained) UIImage property that is being used to hold a user selected image.
This is the code I have at present when the user makes a selection:
- (IBAction) selectImage1 {
UIImage *image = [UIImage imageNamed: #"image1-big.png"];
self.bigImage = image;
}
but I'm wondering if it is possible to omit the use of the temporary variable convenience method and just do this:
- (IBAction) selectImage1 {
self.bigImage = [UIImage imageNamed: #"image1-big.png"];
}
If there are problems with this second method (I'm guessing something to do with memory management), could someone please explain?
Thank you!
The second way is perfectly fine. The line UIImage *image = [UIImage imageNamed: #"image1-big.png"]; gives you a variable image that is auto-released. Assigning it to your ivar via the self.bigImage = image calls bigImage's setter method which retains the value. Thus the line self.bigImage = [UIImage imageNamed: #"image1-big.png"]; is equivalent to the more verbose way.
There is no difference in terms of memory management between the two snippets you posted; unless you get really specific about retain counts in between the two lines in the first snippet.
In an ARC environment, the local variable will be a 'strong' pointer, however it is released when the method leaves scope. In the second snippet, there is no intermediate retain/release'd pointer, and so may actually be slightly more efficient.
The places I have seen the first snippet's technique be necessary are when you have a weak pointer (i.e. a weak #property) where setting self.foo = [UIView ... would immediately allow it to be released. In these cases it is better to use a local variable to keep it around while you work with it:
UIView *someFoo = [UIView...
[self addSubview:someFoo];
self.someWeakProperty = someFoo;
compare with:
self.someWeakProperty = [UIView...
[self addSubview:self.someWeakProperty]; // it's already nil!!

Inspecting the string created by stringWithFormat:

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?
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.
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]];
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!
You can store the UIImage as instance of the class, and compare it. You won't be using more memory than a pointer.
selectNum stands for the selected image, right?If so, try to get selectNum when picking the picture.