I use GCD to fetch some images from the Internet in a new queue using dispatch_queueu_create. Then I go back to the main queue and update the UIImageView with the fetched image by using dispatch_async. I am using self.imageView to reference to the UIImageView in the main queue.
However, sometimes the image takes some time to load from the Internet. If the user clicks somewhere and the view controller changes to something else, I found some weird behavior or my app even crashes. I guess the reason is that I am referencing to self.imageView but the current view controller doesn't have that property. Or any other possibilities? Any suggestions to fix that?
Thanks in advance!
Sorry that I didn't include code here. Here is the code:
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
dispatch_queue_t photoFetchQueue = dispatch_queue_create("photo data downloader", NULL);
dispatch_async(photoFetchQueue, ^{
NSURL *photoURL = ...;
NSData *photoData = ...;
dispatch_async(dispatch_get_main_queue(), ^{
self.imageView.image = [UIImage imageWithData:photoData];
self.imageView.frame = CGRectMake(0, 0, self.imageView.image.size.width, self.imageView.image.size.height);
self.scrollView.zoomScale = 1.0;
self.scrollView.contentSize = self.imageView.image.size;
[scrollView zoomToRect:imageView.frame animated:YES];
});
});
dispatch_release(photoFetchQueue);
}
You need a cancellation pattern. That is, you need to be able to cancel the background task. Without code, hard to say what the best approach would be. If you used the higher level NSOperation API, it has cancellation support.
For Blocks/GCD, you'd probably want to have an "isCanceled" on some object somewhere -- preferably on the object that represents the background fetch -- and then check that, when possible, to determine if the response is still relevant.
Related
I've written a custom view controller class that displays a map with annotations. When an annotation is pressed a callout is displayed and a thumbnail image is shown in the left part of the annotation callout. This class asks a delegate to provide the image that is displayed.
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
[(UIImageView *)view.leftCalloutAccessoryView setImage:[self.delegate mapViewController:self imageForAnnotation:view.annotation]];
}
The delegate class retrieves the image from the network. To protect the UI from being unresponsive a new thread is created to download the image using GCD.
- (UIImage *)mapViewController:(MapViewController *)sender imageForAnnotation:(id<MKAnnotation>)annotation
{
NSURL *someURL = [[NSURL alloc] initWithString:#"a URL to data on a network"];
__block UIImage *image = [[UIImage alloc] init];
dispatch_queue_t downloader = dispatch_queue_create("image downloader", NULL);
dispatch_async(downloader, ^{
NSData *imageData = [NSData dataWithContentsOfURL:someURL]; // This call can block the main UI!
image = [UIImage imageWithData:imageData];
});
return image;
}
Why does the image never display? I was assuming that since the delegate method returns a pointer to an image that at a time in the future is set to valid image data that the thumbnail would eventually update itself. This apparently is not the case...
You're creating a block that's executing asynchronously. This means your code created the block to execute, then immediately returned 'image', which was pointing to the new image you created when you initialized the variable: __block UIImage *image = [[UIImage alloc] init];
Remember that when you return an object from a method, you're actually just returning a pointer to that object.
Sometime after the pointer to this new image was returned. The block runs and assigns the pointer to the image it retrieved to the local variable 'image', which is now out of scope of the method (though the block still has it). So now the block has this reference to the image it got but that reference will go away when the block finishes.
One way to fix this would be to run the block synchronously, but that would be defeating the point of dispatching the image retrieval process. What you need to do is provide a block to the function it can call once the image is retrieved, namely assigning the image where it needs to be. This would look something like this:
- (void)mapViewController:(MapViewController *)sender imageForAnnotation:(id<MKAnnotation>)annotation withImageBlock:(void (^)(UIImage *))block{
{
NSURL *someURL = [[NSURL alloc] initWithString:#"a URL to data on a network"];
__block UIImage *image = [[UIImage alloc] init];
dispatch__object_t currentContext = dispatch_get_current_queue();
dispatch_queue_t downloader = dispatch_queue_create("image downloader", NULL);
dispatch_async(downloader, ^{
NSData *imageData = [NSData dataWithContentsOfURL:someURL]; // This call can block the main UI!
image = [UIImage imageWithData:imageData];
dispatch_async(currentContext, ^{
block(image);
});
});
}
Please note that I grab the current queue context so that I can execute the block given to me on the same thread it was given to me on. This is really important since the block passed to me could contain UIKit methods, which can only be performed on the main thread.
Unfortunately, what you're trying to do here is not easy at all. You'd need to create a "future" (http://en.wikipedia.org/wiki/Futures_and_promises) and return that, which ObjC/Cocoa do not have a built in implementation of.
The best you can likely do here is either a) have the caller pass in a block that runs on completion of the download and updates the UI, or b) return a placeholder image and schedule a block to replace the image after it finishes downloading. Both of those will require restructuring your code somewhat. The latter also requires your downloading code to know how to update your UI, which is a bit unfortunate in terms of increasing coupling.
I have this piece of code to push a view controller:
// Setup the animation
[self.navigationController pushViewController:self.productView animated:YES];
self.productView.imageURL = [product imageURL];
// Set the title of the view to the product's name
self.productView.title = [product name];
// Set the label text of all the labels in the view
[self.productView.caloriesL setText:[product calories]];
[self.productView.fatL setText:[product fat]];
[self.productView.saturatesL setText:[product saturates]];
[self.productView.sugarL setText:[product sugar]];
[self.productView.fibreL setText:[product fibre]];
[self.productView.saltL setText:[product salt]];
But the delegate method viewDidAppear does not get called when the productView appears. I looked up the problem on google and theres a lot of different solutions, none of which I could apply to my problem.. I had a similar problem in a previous solution but I got around it by manually calling viewDidApear in the viewDidLoad method. Unfortunately in this case I can't do that as viewDidLoad is called only once (on the first push). Does anyone know how to fix this?
Thanks,
Jack Nutkins
EDIT:
Here is the viewDidAppear method in the productView (and selector):
- (void)viewDidAppear:(BOOL)animated{
//Start animating the activity indicator
[indicator startAnimating];
//Perform this method in background
[self performSelectorInBackground:#selector(loadImage) withObject:nil];
}
- (void) loadImage {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// Load the animals image into a NSData boject and then assign it to the UIImageView
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]];
UIImage *image = [[UIImage alloc] initWithData:imageData];
self.imageView.image = image;
//Stop animating the activity indicator
[indicator stopAnimating];
[pool drain]; //see comment below
}
First: You definitely don't want to be calling any of the standard viewWillLoad, viewDidLoad, viewWillAppear, etc. methods manually. Let the OS do it for you.
Second: Can you show us how your viewDidAppear method is implemented in your self.productView instance? (Just a hunch, you're not expecting this method to be called on your navigation controller, right?) I just want to make sure your method signature is exactly correct. If it's not (due to a mispelling, improper args, etc.) then it definitely won't be called.
Third: I would move your pushViewController: call to after the rest of the code you provided. You don't want the view to be pushed on the screen (so the user can see it) and then have a bunch of on-screen values immediately change. Set your ivars and title property first, then push the view controller. This eliminates any weird flickering.
I solved it, though it doesn't seem conventional, can't believe I didn't try it earlier :
I put this line :
[self.productView viewDidAppear:YES];
Underneath :
// Setup the animation
[self.navigationController pushViewController:self.productView animated:YES];
I also moved the code to set the labels text to run before the above line. (As well as changing my code to send strings to the pushed controller rather that accessing its UI elements.)
Thanks for everyones help,
Jack
I need to toggle a specific amount of times between two (or maybe later on more) pictures after a button was pressed, and wait a second or two for the change. When a stop-button is pressed at any time, the toggling should stop. My code by now looks like this
IBOutlet UIImageView *exerciseView;
- (void) repetitionCycle {
stopButtonPressed = NO;
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
for (NSInteger counter = kRepetitions; counter >=0; counter--) {
exerciseView.image = [UIImage imageNamed:#"blue.jpg"];
[NSThread sleepForTimeInterval:kSleepDuration];
if (stopButtonPressed) {break;}
image = [UIImage imageNamed:kExerciseEndingPosition];
exerciseView.image = [UIImage imageNamed:#"image1.jpg"];
[NSThread sleepForTimeInterval:kSleepDuration];
if (stopButtonPressed) {break;}
}
self.stopRepetitionCycle;
[pool release];
}
exerciseView is
Besides other things, in stopRepetitionCycle I just set stopButtonPressed to YES, so it stops after it finished the "for" for the first time.
It does count down, it does stop after one cycle, but it doesn't change the picture.
While fiddling around, I set the initial picture via IB, so it finally displayed ANYTHING.. The fun part, when I hit the stop button in the right moment, the second picture is shown. So I guessed I need to set the view manually every time the image should toggle. But
[self.exerciseView addSubview:image];
gives me the error
Incompatible Objective-C types "struct UIImage *", expected "struct UIView *" when passing argument 1 of "addSubview:" from distinct Objective-C type
Also
[self.exerciseView.image addSubview:image];
doesn't do the job and gives me a
UIImage may not respond to addSubview
Any idea what I have to do here?
Thank you very much!
uuhm...
your usage of [NSThread sleep...] puzzles my...
in fact: if you are on a secondary thread (meaning, not the main thread), then you are doing something not allowed, which is trying to access the UI from a secondary thread.
this could explain the strange behavior you are seeing.
on the other hand, if this is the main thread, possibly is not a good idea to call sleep... because that way you will freeze entirely the UI, and you could not possibly intercept the click on the button...
anyhow, what I would suggest, is using NSTimers to move from one image to the next one at certain intervals of time. when the stop button is hidden you would simply cancel the timer and the slideshow would end. pretty clean.
as to the error messages you are having with your image, the fact is that UIImage is not a UIView, so you cannot add it as a subview, but this is not what does not work here...
Use UIImageView. It has built-in support for this.
imageView.animationImages = [NSArray arrayWithObjects:[UIImage imageNamed:#"blue.jpg"], [UIImage imageNamed:#"image1.jpg"], nil];
imageView.animationDuration = kSleepDuration * [imageView.animationImages count];
Wire this function to the start button
- (IBAction) startAnimation {
[imageView startAnimating];
}
and this to the stop button
- (IBAction) stopAnimation {
[imageView stopAnimating];
}
Updating the UI within a loop is almost guaranteed to fail. You should most likely be using an NSTimer to swap the image at a given interval instead.
Furthermore, [self.exerciseView addSubview:image] is failing because you're passing a UIImage and not a UIView. Create a UIImageView (which is a subclass of UIView) with your UIImage and pass that instead.
The method addSubview is used to add only UIViews. You can't use it with a UIImage class. The general syntax is :
[(UIView) addSubview:(UIView*)];
replace
[self.exerciseView addSubview:image];
with
self.exerciseView.image = image;
For the same reason
[self.exerciseView.image addSubview:image];
won't work either.
I've read a lot of UIScrollView with UIImageView threads here or other googled pages. But I still cannot get the problem I'm confronting. I'm having a cold right now. Hope I can still make it clear, lol. Here is the problem:
I'm building one app which mainly uses UIScrollView to display a few images. Here the amount counts, not the size, which is averagely 100KB(I even converted PNG to jpg, not sure whether it helps or not). With no more than 10 images, my app crashes with memory warning. This is the first time I encounter memory issue, which surprised me as the compiled app is less than 10MB.
At the very beginning, I load all the images on launch, looping all names of image files and do
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:imgName]];
[scrollview addSubview:imageView];
[imageView release];
If I'm right, I think after launch, all the images are in memory, right? But the funny thing here is, the app could launch without any problem(at most a level 1 memory warning). After I scroll a few images, it crashed. I checked leaks for sure and also allocations. No leak and allocation almost had no change during scrolling.
So, is there something special done by imageNamed rather than cache?
And then, yes, I turned to lazy load.
For fear of checking page and loading images on demand might jerk the scrolling(which was proved true), I used a thread which runs a loop to check offset of the scroll view and load/unload images.
I subclassed UIImageView by remembering the image name. It also contains loadImage and unloadImage which will be executed on that thread.
- (void)loadImage {
/if ([self.subviews count] == 0) {
UIImageView iv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:self.imageName]];
[self performSelectorOnMainThread:#selector(renderImage:) withObject:iv waitUntilDone:NO];
//[self addSubview:iv];
[iv release];
}*/
if (self.image == nil) {
//UIImage *img = [UIImage imageNamed:self.imageName];
UIImage *img = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[self.imageName stringByDeletingPathExtension] ofType:[self.imageName pathExtension]]];
// image must be set on main thread as UI rendering is main thread's responsibility
[self performSelectorOnMainThread:#selector(renderImage:) withObject:img waitUntilDone:NO];
[img release];
}
}
// render image on main thread
- (void)renderImage:(UIImage*)iv {
//[self addSubview:iv];
self.image = iv;
}
(void)unloadImage {
self.image = nil;
//[(UIView*)[self.subviews lastObject] removeFromSuperview];
}
You can see the commented code that I've played with.
In unloadImage, if I write [self.image release], then I get EXC_BAD_ACCESS, which is unexpected, as I think alloc and release are matched here.
The app still crashes with no leak. The initWithContentsOfFile version even crashed earlier than imageNamed version, and made the scrolling not that smooth.
I run the app on device. By checking allocations, I found imageNamed version used much less memory than initWithContentsOfFile version, though they both crash. Instruments also showed that the allocated images were 2,3 or 4, which indicated the lazy load did do his job.
I checked PhotoScroller of WWDC2010, but I don't think it solvs my problem. There is no zooming or huge picture involved.
Anybody helps! Thank you in advance.
The crash log says nothing. The app crashes mostly after memory warning level = 2. And if run on simulator, there will be no problem.
It doesn't matter which format do you use for your images. They're converted to bitmaps when you display them.
I'd suggest to use the technique similar to that one which is used by UITableView (hide the image and free the memory it uses when it disappears from the screen and instantiate the image only when you need to show it).
As an alternate way – if you need to show these images in a grid – you might take a look to a CATiledLayer.
Anyhow, loading all the images to the memory is not the best idea :)
You can load all the images to an array. And you can design a view having one image view and try the below code:
array name: examplearray and view name :exampleview
-(void)updateImagesInScrollView
{
int cnt = [examplearray count];
for(int j=0; j< cnt; ++j)
{
NSArray *nibContents = [[NSBundle mainBundle] loadNibNamed:#"exampleview"
owner:self
options:nil];
UIView *myView = [nibContents objectAtIndex:0];
exampleview * rview= (exampleview *)myView;
/* you can get your iamge from the array and set the image*/
rview.imageview.image = yourimage;
/*adding the view to your scrollview*/
[self.ScrollView addSubview:rview];
}
/* you need to set the content size of the scroll view */
self.ScrollView.contentSize = CGSizeMake(X, self.mHorizontalScrollView.contentSize.height);
}
Im developing an app for an iPhone and I found that the following code is causing the memory allocation to increment.
-(UIImage *)createRecipeCardImage:(Process *)objectTBD atIndex:(int)indx
{
[objectTBD retain];
// bringing the image for the background
UIImage *rCard = [UIImage imageNamed:#"card_bg.png"];
CGRect frame = CGRectMake(00.0f, 80.0f, 330.0f, 330.0f);
// creating he UIImage view to contain the recipe's data
UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
imageView.image = rCard;
[rCard release];
imageView.userInteractionEnabled = YES;
float titleLabelWidth = 150.0;
float leftGutter = 5.0;
float titleYPos = 25.0;
float space = 3.0;
float leftYPos = 0;
// locating Title label
float currentHeight = [self calculateHeightOfTextFromWidth:objectTBD.Title :titleFont :titleLabelWidth :UILineBreakModeWordWrap];
UILabel *cardTitle = [[UILabel alloc]initWithFrame:CGRectMake(leftGutter, titleYPos, titleLabelWidth, currentHeight)];
cardTitle.lineBreakMode = UILineBreakModeWordWrap;
cardTitle.numberOfLines = 0;
cardTitle.font = titleFont;
cardTitle.text = objectTBD.Title;
cardTitle.backgroundColor = [UIColor clearColor];
[imageView addSubview:cardTitle];
[cardTitle release];
leftYPos = titleYPos + currentHeight + space;
// locating brown line
UIView *brownLine = [[UIView alloc] initWithFrame:CGRectMake(5.0, leftYPos, 150.0, 2.0)];
brownLine.backgroundColor = [UIColor colorWithRed:0.647 green:0.341 blue:0.122 alpha:1.0];
[imageView addSubview:brownLine];
[brownLine release];
leftYPos = leftYPos + 2 + space + space + space;
// creating the imageView to place the image
UIImageView *processPhoto = [[UIImageView alloc] initWithFrame:CGRectMake(leftGutter, leftYPos, 150, 150)];
if((uniqueIndex == indx) && (uniqueImg.imageData != nil))
{
if([uniqueImg.rcpIden isEqualToString:objectTBD.iden])
{
objectTBD.imageData = [NSString stringWithFormat:#"%#", uniqueImg.imageData];
[recipesFound replaceObjectAtIndex:indx withObject:objectTBD];
NSData * imageData = [NSData dataFromBase64String:objectTBD.imageData];
UIImage *rcpImage = [[UIImage alloc] initWithData:imageData];
[imageData release];
processPhoto.image = rcpImage;
[rcpImage release];
}
}
else if(objectTBD.imageData != nil)
{
NSData * imageData = [NSData dataFromBase64String:objectTBD.imageData];
UIImage *rcpImage = [[UIImage alloc] initWithData:imageData];
processPhoto.image = rcpImage;
[rcpImage release];
[decodedBigImageDataPointers addObject:imageData];
}
else
{
UIImage * rcpImage = [UIImage imageNamed:#"default_recipe_img.png"];
processPhoto.image = rcpImage;
[rcpImage release];
}
NSlog(#" Process Photo Retain Count %i", [processPhoto retainCount]); // this prints a 1
[imageView addSubview:processPhoto];
NSlog(#" Process Photo Retain Count %i", [processPhoto retainCount]); // this prints a 2!!!!
//[processPhoto release]; // this line causes an error :(
// converting the UIImageView into a UIImage
UIGraphicsBeginImageContext(imageView.bounds.size);
[imageView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[objectTBD release];
for(UIView *eachSubview in imageView.subviews)
{
[eachSubview removeFromSuperview];
NSLog(#"each subview retainCount %i despues", [eachSubview retainCount]);
// here I find that the processPhoto view has a retain count of 2 (all other views have their retain count in 1)
}
return viewImage;
}
When I checked at the instruments object allocation I found that the "GeneralBlock-9216" growing up.
Breaking down the row I found that every time I call this code, one instance of:
2 0x5083800 00:18.534 ImageIO initImageJPEG
is being allocated. Checking the call stack, the following line is highlighted:
UIImage * objImage = [UIImage imageWithData:imageData];
Any help to find what the error is?
As TechZen said, the imageWithXXX: methods cache the image inside of them while you run the program (though you release the instances after using). I recommend initWithXXX: and release API sets instead of imageWithXXX:.
Well, if you embed several debug log on your source code, check how many times is it called, and check the retain count of the instances.
As far as I can explain, that is all.
I hope you will solve the problem.
Does anyone have an answer for this? It's tearing me apart trying to figure out why this image information keeps lingering. I've tried every solution.
The situation:
Images get downloaded and stored to the device, then loaded with imageWithContentsOfFile (or even initWithContentsOfFile, which doesn't help either). When the view goes away, the images don't, but they don't show up as leaks, they're just this initImageJPEG Malloc 9.00 KB that never goes away and keeps ramping up.
UPDATE: I believe I've figured this out: Check to make sure everything is actually getting dealloc'd when you're releasing whatever the parents (and/or grandparents) and etc of the images are. If the parents don't get deallocated, they never let go of their children images, and whatever data was in those images sticks around. So check retain counts of parent objects and make sure that everything's going away all the way up whenever you release the view at the top.
A good way to check for this is to put NSLogs into custom classes' dealloc methods. If they never show up, that object isn't going away, even though the reference to it might, and it (and whatever its subviews and properties are) will never ever disappear. In the case of images, this means a pretty sizable allocation every time that object is generated and never deallocated. It might not show up in leaks, especially if the parent of the topmost object you're thinking you're releasing but actually aren't persists and doesn't itself ever deallocate.
I hope this helps. It'll be useful to take some time to read through your code with a fine-toothed comb to make sure you're allocating and releasing things properly. (Search for "alloc]", start at the top of the file, and work your way down to make sure you're releasing and that the release isn't inside of some if() or something.)
Also, running "Build and Analyze" might lock up your machine for a bit, but its results can be really helpful.
Good luck!
I think you're seeing UIImage cacheing images. There used there used to be a method something like initWithData:cache that let you turn the cacheing off. Now I think the system always caches the images automatically behind the scenes even after you've deallocted the specific instances.
I don't think its an error on your part. I think it's the system keeping data around in the OpenGl subsystem. Unless it causes a major leak, I don't think it is a problem.