Xcode: Array of images fails to instantiate on device - objective-c

I've got an app that's working perfectly on the simulator, but fails on my iPod Touch (4th gen), and I'd like to know why. The part that's failing is a simple interactive menu that shows six pictures on the root of a UINavigationController, then pushes a viewController which instantiates an array of food images, creates a view which holds all the images side-by-side, and moves the viewing area over the image that correlates to the image clicked in the root view. When I run it on the device, the array only instantiates with pointers to two images, and an exception is thrown when the array is used to create the images side-by-side.
//code from the pushed view controller
- (void)setupScrollView:(UIScrollView*)scrMain {
// we have 6 images here.
// we will add all images into a scrollView & set the appropriate size.
NSMutableArray *array = [NSArray arrayWithObjects:
[UIImage imageNamed:#"shrimpquesadilla.jpg"],
[UIImage imageNamed:#"pulledpork.jpg"],
[UIImage imageNamed:#"filetMignon.jpg"],
[UIImage imageNamed:#"Reuben.jpg"],
[UIImage imageNamed:#"cajunshrimp.jpg"],
[UIImage imageNamed:#"primerib.jpg"], nil];
NSLog(#"stuff: %#", array);
for (int i=1; i<=6; i++) {
UIImage *image = [array objectAtIndex:(i-1)];
UIImageView *imgV = [[UIImageView alloc]
initWithFrame:CGRectMake((i-1)*scrMain.frame.size.width,
0, scrMain.frame.size.width, (scrMain.frame.size.height - 90))];
imgV.contentMode=UIViewContentModeScaleToFill;
[imgV setImage:image];
imgV.tag=i+1;
[scrMain addSubview:imgV];
}
[scrMain setContentSize:CGSizeMake(scrMain.frame.size.width*6,
scrMain.frame.size.height)];
[scrMain scrollRectToVisible:CGRectMake(self.count*scrMain.frame.size.width,
0, scrMain.frame.size.width, scrMain.frame.size.height) animated:YES];
}
The output of the NSLog when run through the simulator:
2012-08-20 09:51:23.812 DemoTabbed[1545:11603] stuff: (
"<UIImage: 0x7931150>",
"<UIImage: 0x6e63270>",
"<UIImage: 0x6e67700>",
"<UIImage: 0x6e68040>",
"<UIImage: 0x6e5c700>",
"<UIImage: 0x6e64210>"
)
And the output when run on the device:
2012-08-20 10:26:50.211 DemoTabbed[2128:707] stuff: (
"<UIImage: 0x197e20>",
"<UIImage: 0x181270>"
)
And then there's the standard error for the index out of bounds. I don't know if it's relevant or not, but two of my icons aren't loading on the device, either, though they work on the simulator. Let me know if you need any more code, or if you have questions about the app or its behavior, I'd be happy to add more.
EDIT: I have tried rearranging the order in which the images are instantiated into the array, and nothing was changed by it. The output stll showed that only two images were pointed to by the array.

iOS has a case-sensetive file system. You have a case problem in #"filetMignon.jpg" file, making it resolve to nil image and ending the array elements early.
To fix that, make sure that images are named in same case as you load them (the better idea would be to always have a lowercase image names).
It's not an issue on Simulator, as OS X is using case-insensetive (in 99% cases) filesystem, meaning, #"filetMignon.jpg" and #"filetmignon.jpg" would resolve to same file.

Related

Rotate image in IKImageBrowserView. Cocoa/Objective C

Im looking for your help, with Cocoa IKImageBrowserView.
I have that browser, and images inside that. The images are taken from the folder that I do provide to it. Kinda like that:
[importedImages removeAllObjects];
[images removeAllObjects];
NSArray *onlyPNGs = [self getAllPngsInLibraryFolder];
NSString *imagesPath = [[FileHelperManager defaultManager] getPathToImagesFolder];
for(NSString *str in onlyPNGs)
{
NSString *mergedPath = [imagesPath stringByAppendingString:str];
[self addAnImageWithPath:mergedPath];
}
[self updateDatasource];
When I do chose particular image from ImageBrowser, I show it in NSImageView, and provide an ability to modify some parameters of this image in database where I do store information about all of them.
The problem what I have met is - I want to support the rotation change of chosen image. I can rotate without any problem an NSImageView preview of selected image, but how can I rotate then this image inside ImageBrowser?
Would be good if somebody can help me with that.
Here is an illustration of what I do try to achieve.
So, steps 1,2 are ok, but how can I do step 3?

Correctly Load an Image into an Existing storyboard UIImageView?

I am using an array to try to load images into specific UIImageViews. I have 10 UIImageViews set up on my storyboard.
I also have a Game Over method that runs whenever the frame of one UIImageView intersects with another UIImageView. For some reason, whenever I try to use the array to load my UIImageViews, my Game Over method immediately triggers. I can't figure out why. As soon as I remove the initWithImage line, the game runs normally. Any ideas?
- (void)viewDidLoad
{
KanaCharacters = [[NSArray alloc] initWithObjects:[UIImage imageNamed:#"a.png"],...
nil];
int imageDisplay = arc4random_uniform([KanaCharacters count]);
Monster1 = [[UIImageView alloc] initWithImage:[KanaCharacters objectAtIndex:imageDisplay]];
}
-(void) Collision
{
if ((CGRectIntersectsRect(Monster1.frame, Ship.frame)) && (Monster1Hit==NO))
{
[self GameOver];
}
}
-(void)GameOver
{
WinOrLose.hidden=NO;
WinOrLose.text = [NSString stringWithFormat:#"You Lose!"];
}
I suspect that Collision if firing once an image in Monster1 and Ship.frame.
This is because I suspect your Monster is being placed where your ship is?
you may want to move the ship or the monster before you add the image into the view.

Received memory warning but the live bytes are only 5 to 10MB [duplicate]

This problem has completely stumped me. This is for iOS 5.0 with Xcode 4.2
What's going on is that in my app I let user select images from their photo album and I save those images to apps document directory. Pretty straight forward.
What I do then is that in one of the viewController.m files I create multiple UIImageViews and I then set the image for the image view from one of the picture that user selected from apps dir. The problem is that after a certain number of UIImage sets I receive a "Received memory warning". It usually happens when there are 10 pictures. If lets say user selected 11 pictures then the app crashes with Error (GBC). NOTE: each of these images are at least 2.5 MB a piece.
After hours of testing I finally narrowed down the problem to this line of code
[button1AImgVw setImage:image];
If I comment out that code. All compiles fine and no memory errors happen. But if I don't comment out that code I receive memory errors and eventually a crash. Also note it does process the whole CreateViews IBAction but still crashes at the end. I cannot do release or dealloc since I am running this on iOS 5.0 with Xcode 4.2
Here is the code that I used. Can anyone tell me what did I do wrong?
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self CreateViews];
}
-(IBAction) CreateViews
{
paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask ,YES);
documentsPath = [paths objectAtIndex:0];
//here 15 is for testing purposes
for (int i = 0; i < 15; i++)
{
//Lets not get bogged down here. The problem is not here
UIImageView *button1AImgVw = [[UIImageView alloc] initWithFrame:CGRectMake(10*i, 10, 10, 10)];
[self.view addSubview:button1AImgVw];
NSMutableString *picStr1a = [[NSMutableString alloc] init];
NSString *dataFile1a = [[NSString alloc] init];
picStr1a = [NSMutableString stringWithFormat:#"%d.jpg", i];
dataFile1a = [documentsPath stringByAppendingPathComponent:picStr1a];
NSData *potraitImgData1a =[[NSData alloc] initWithContentsOfFile:dataFile1a];
UIImage *image = [[UIImage alloc] initWithData:potraitImgData1a];
// This is causing my app to crash if I load more than 10 images!
// [button1AImgVw setImage:image];
//If I change this code to a static image. That works too without any memory problem.
button1AImgVw.image = [UIImage imageNamed:#"mark-yes.png"]; // this image is less than 100KB
}
NSLog(#"It went to END!");
}
This is the error I get when 10 images are selected. App does launch and work
2012-10-07 17:12:51.483 ABC-APP[7548:707] It went to END!
2012-10-07 17:12:51.483 ABC-APP [7531:707] Received memory warning.
App crashes with this error when there are 11 images
2012-10-07 17:30:26.339 ABC-APP[7548:707] It went to END!
(gbc)
This situation (memory warnings and application quitting while attempting to load multiple full resolution UIImages into a view) has attempted to burn me a couple times in my iOS programming career.
You need to make a shrinked down copy of your original image before doing the "setImage" call.
For my own code, I use the "UIImage+Resize" category, the details for which can be found here.
Resize your image to something smaller before inserting into your view, then make sure the full resolution image is released (or set to nil if on ARC) and you should have a happier time of things.
Here is how I do it in my own code:
CGSize buttonSize = CGSizeMake(width, height);
// it'd be nice if UIImage took a file URL, huh?
UIImage * newImage = [[UIImage alloc] initWithContentsOfFile: pathToImage];
if(newImage)
{
// this "resizedimage" image is what you want to pass to setImage
UIImage * resizedImage = [newImage resizedImage: buttonSize interpolationQuality: kCGInterpolationLow];
}

Memory management with image saved from UIImagePickerController

I'm writing an app in which the user takes a photo of them self, and then goes through a series of views to adjust the image using a navigation controller. This works perfectly fine if the user takes the photo with the front camera (set as default on devices that support it), but when I repeat the process I get about half way through and it crashes after throwing a memory warning.
After profiling in Instruments I see that my apps memory footprint holds at about 20-25 MB when using the lower resolution front camera image, but when using the back camera every view change adds another 33 MB or so until it crashes at about 350 MB (on a 4S)
Below is the code I'm using to handle saving the photo to the documents directory, and then reading that file location to set the image to a UIImageView. The "read" portion of this code is recycled through several view controllers (viewDidLoad) to set the image I saved as the background image in each view as I go.
I have removed all my image modification code to strip this down to the bear minimum attempting to isolate the problem, and I can't seem to find it. As it stands right now, all the app does is take a photo in the first view and then use that photo as the background image for about 10 more views, allocating as the user navigates through the view stack.
Now obviously the higher resolution photos would use more memory, but what I don't understand is that why the low resolution photos don't seem to be using more and more memory as I go, whereas the high resolution photos continuously use more and more until a crash.
How I am saving and reading the image:
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
jpgData = UIImageJPEGRepresentation(image, 1);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
filePath = [documentsPath stringByAppendingPathComponent:#"image.jpeg"];
[jpgData writeToFile:filePath atomically:YES];
[self dismissModalViewControllerAnimated:YES];
[disableNextButton setEnabled:YES];
jpgData = [NSData dataWithContentsOfFile:filePath];
UIImage *image2 = [UIImage imageWithData:jpgData];
[imageView setImage:image2];
}
Now I know that I could try scaling the image before I save it, which I plan on looking into next, but I don't see why this doesn't work as is. Maybe I was falsely under the impression that ARC automatically deallocated views and their subviews when they leave the top of the stack.
Can anyone shed some light on why I'm stock piling my devices memory? (Hopefully something simple I'm completely overlooking) Did I somehow manage to throw ARC out the window?
EDIT: How I call for the image in my other views
- (void)loadBackground
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"image.jpeg"];
UIImage *image = [UIImage imageWithContentsOfFile:filePath];
[backgroundImageView setImage:image];
}
How navigation between my view controllers is established:
EDIT 2:
What my basic declarations look like:
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#interface PhotoPickerViewController : UIViewController <UIImagePickerControllerDelegate, UINavigationControllerDelegate>
{
IBOutlet UIImageView *imageView;
NSData *jpgData;
NSString *filePath;
UIImagePickerController *imagePicker;
IBOutlet UIBarButtonItem *disableNextButton;
}
#end
If relevant, how I call up my image picker:
- (void)callCameraPicker
{
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera] == YES)
{
NSLog(#"Camera is available and ready");
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePicker.delegate = self;
imagePicker.allowsEditing = NO;
imagePicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]; for (AVCaptureDevice *device in devices)
{
if([[UIScreen mainScreen] respondsToSelector:#selector(scale)] && [[UIScreen mainScreen] scale] == 2.0)
{
imagePicker.cameraDevice = UIImagePickerControllerCameraDeviceFront;
}
}
imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentModalViewController:imagePicker animated:YES];
}
else
{
NSLog(#"Camera is not available");
UIAlertView *cameraAlert = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"Your device doesn't seem to have a camera!"
delegate:self cancelButtonTitle:#"Dismiss"
otherButtonTitles:nil];
[cameraAlert show];
}
}
EDIT 3: I logged viewDidUnload, and it was in fact not being called so I'm now calling loadBackground in viewWillAppear and making my backgroundImageView nil in viewDidDisappear. I expected this to help but it made no difference.
- (void)viewWillAppear:(BOOL)animated
{
[self loadBackground];
}
- (void)viewDidDisappear:(BOOL)animated
{
NSLog(#"ViewDidDisappear");
backgroundImageView = nil;
}
The relationship between UIImage and UIImageView is not necessarily intuitive for everyone.
UIImage is a high level representation of your image data - alone, it does nothing in terms of displaying the data.
UIImageView works with UIImage to allow you to display an image.
There is no reason why multiple instances of UIImageView cannot display the same UIImage. This is nice and efficient, because there is only one in-memory representation of the image data, being shared by multiple views.
What you seem to be doing is creating a new UIImage for each one of your views, by loading it from disk. So this is a poor general design in two respects: instantiating what is effectively the same UIImage over and over again, and re-loading the same image data from disk repeatedly.
Your memory problem is really a separate issue, where you are not properly releasing the image data you keep loading into UIImage objects and UIImageViews.
In theory, you should be able to take the very first UIImage you're getting from UIImagePickerController and simply pass that reference around to your views, without reloading from disk.
If you need to be saving and reloading from disk because of higher level functional requirements (e.g. because the image is being changed by the user and you want to keep saving it), you'll need to be sure you are fully tearing down the previous UIView, by removing it from the it's view hierarchy. It is helpful to setup a breakpoint in the dealloc method for the view to confirm it is being removed and dealloced, and make sure you set any iVar references to sub-views (it appears your backgroundImageView is an iVar) are set to nil. If you are not properly tearing down that backgroundImageView, it is continuing to hold a reference to the UIImage you set to it's image property.
There are a couple of things that are curious about the code you posted:
None of your view-callback implementations call super. That’s bad! Make extra sure that you are calling super in viewDidUnload and (if you implemented it) didReceiveMemoryWarning.
Make sure you implement didReceiveMemoryWarning in a meaningful way!
You really should not be re-creating that image over and over again! I assume you are not editing the actual image because you use JPEG compression on it which — even at 100% quality — will deteriorate your image with every save…
Check your implementation of viewDidUnload make sure to set every of your IBOutlets to nil.
ARC is not Pixie Dust™! It just saves you a bit of typing, it does not free you from designing and maintaining your object graphs!
From your question, I see at the very least these graphs that refer to your image:
image 1 <- image-view 1 <- view-controller 1 <- navigation-controller <- key window <- application
image 1 <- image-view 1 <- view 1 <- view-controller 1 <- navigation-controller <- key window <- application
This is repeated for every view-controller with an index shift on the view-controller, view, image view and image. While you have to have separate views, image-views for your view-controllers, I cannot think of a reason why you would want several copies of the same image.
So the first axe on your memory consumption clearly is to no longer create all those copies of the same image data — I’d estimate that this will get you half of the low-hanging memory savings.
The next thing is that ARC can only free the memory consumed by your objects if it is no longer referenced.
Memory wise, views are not exactly lightweight objects and when you build up a deep navigation stack you end up with gobs of them.
So you need to axe any unneeded strong references to those views, as well.
The level, at which this has to happen is the view-controller. The latest time at which this should happen is in the view-controller’s implementation of viewDidUnload.
Why the view-controller?
From what you described, the image itself is only referenced by the UIImageView — this is a bad choice, IMHO, but I digress…
UIViewController is designed to “know”, when its view is needed and when it’s safe to dispose of it — that’s why it implements didReceiveMemoryWarning and viewDidUnload:
If the memory pressure gets to high and the view-controller’s view is not “on screen” the root implementation of didReceiveMemoryWorning will let go of its view and call viewDidUnload upon itself, afterwards.
This is why you must call through to super in your implementations of both of those methods.
In addition, this is why if you have strong IBOutlets that refer to subviews of the view-controller’s view, you must nil them in viewDidUnload or the system cannot reclaim the memory they occupy.
At its heart UIViewController is a big-ass finite state-machine. All of those “something-will/did-whatever” callbacks are used to transition between those states and most of the default implementations do some very important book-keeping to keep all that state in order.
If you are not invoking them in your overrides, you˚ll end up in inconsistent states and bad things — like this out of memory crasher — happen.
Just create separate folder and save your Capture images in it. After your successful operation clear that folder data(or)folder.using the nsfilemager.

How to refresh view in objective-c

I wanted to create a gallery. It loads different images based on the category, that a user selects. I used to populate images in UIImageViews.
My when selecting different categories is that it does not clear the previously selected images. This is my code for populating images.
-(void)refresh{
categoryLabel.text = treatment.treatmentName;
NSMutableArray *galleryImages =[NSMutableArray alloc] ;
galleryImages = [[PatientImage alloc]find:treatment.treatmentId];
int imgCount = [galleryImages count];
for(int i=0;i<imgCount;i++){
PatientImage *apatientImage = [galleryImages objectAtIndex:i];
UIImage *img1 = [UIImage imageNamed:apatientImage.imageBefore];
UIImageView *myImageView = [[UIImageView alloc] initWithImage:img1];
myImageView.contentMode = UIViewContentModeTopRight;
myImageView.frame = CGRectMake(120+i*240,120.0,100.0, 100.0);
[self.view addSubview:myImageView];
UIImage *img2 = [UIImage imageNamed:apatientImage.imageAfter];
UIImageView *myImageView2 = [[UIImageView alloc] initWithImage:img2];
myImageView2.contentMode = UIViewContentModeTopRight;
myImageView2.frame = CGRectMake(120+i*240+300,120.0,100.0, 100.0);
[self.view addSubview:myImageView2];
}
}
First things first, You have some memory leaks there. You are allocating UIImageViews but are not releasing them anywhere, after you have added them to your view. I don't know if that applies to ARC, though. Same applies to your Mutable array, but I suppose you are releasing it after the 'for' loop somewhere, since it seems you posted code after omitting some of it.
As far as your actual question is concerned, I wouldn't do this this way. I would make the mutable array an object variable, and then fill it with my image views. When calling refresh again, I would first call -removeFromSuperview on each image view, then empty the array, then repopulate it and add the new subviews to my view. That is the simple way.
I don't know if you are using ARC, but you should be careful about memory management when using dynamically loaded views. Each time you add a view to another one, you increase its retain counter. You must then call release to remove ownership, and let the iOS runtime handle the rest.
Also note that operations such as this using views are expensive in terms of memory. So, another way of repopulating the gallery view is to just change the image an imageView holds. That will save you some memory, and time. In case the view doesn't have a constant number of images to be displayed, you can refine your algorithm to change the images on the already created image views, and then add more image views if necessary or delete the remaining ones, if any.
I hope I helped.
try at the start of refresh call
[[self subviews] makeObjectsPerformSelector: #selector(removeFromSuperview)];
or
for (id imageView in self.subviews){
if([imageView isKindOfClass:[UIImageView class]]) [imageView removeFromSuperview];
}
call [tableview reloadData] if You are using tableview to show your gallery images
or call view's
[self.view setNeedsDisplay] method for refreshing the view.