How do i properly discard a subview? - iphone

I have a problem with my app where the code for which is far too long to go into, but suffice to say when i'm removing a UIView and replacing it with a new one like so:
NSLog(#" .. %#", (Icon *)[self viewWithTag:index]);
Icon *icon = (Icon *)[self viewWithTag:index];
CGRect frame = icon.frame;
int tag = icon.tag;
[icon removeFromSuperview];
[icon release];
Icon *icon2 = [[Icon alloc] init];
icon2.frame = frame;
[icon2 makeIconStandardWithTag:(int)tag];
[self addSubview:icon2];
It does some weird thing where that NSLog the first time (because the view is already there) shows that the object is an icon, but the second time after running this code shows that it's a UIImageView for some reason now, and it displays what i presume to be the original icon at some odd position on the screen. It's very erratic behaviour. But what i do know is this:
Removing the [icon removeFromSuperview]; line, although keeping the object there, stops this behaviour and causes the NSLog to return an Icon, as it should.
So my guess is that it's not removing icon correctly. Is there a way to completely remove icon, or is removeFromSuperview as far as i can go. What i could do is just have it set to alpha = 0 but this is more of a patch-over solution and not how i want to solve it.

"Is there a way to completely remove
icon, or is removeFromSuperview as far
as i can go"
You can set the object to nil:
icon = nil;

Can you verify what "self" is in this line of code:
It might not be what you think.
[self addSubview:icon2];
NSLog(#" Self is %#", self);

This is a guess, but try setting self.tag to -1 or some other value that doesn't collide with the tags you're setting on your Icon objects. The viewWithTag: method searches the current view and its subviews for a match, so if self.tag == 0 and you call [self viewWithTag:0], you'll get self.

Did you retain icon somewhere prior to this? If not, no need to release it after the call to removeFromSuperview. Similarly, unless you need the reference to icon2 elsewhere, you can release that after calling addSubview.
Views retain views added via addSubview, and they release views removed via removeFromSuperview.

Related

Pushing View Controller - viewDidAppear not called

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

Memory Leak Warnings, Due To NSArray Of Large Images

I have an iPad app, which is children's book. You navigate from one page to the next by calling this action, which essentialy fades out the current page and fades in the next page, then fills the three stack UIImageViews with the next row of the NSArray, so it's prepared to complete the action for the next page:
-(void)delayedMethod{
[leftButton setAlpha:1];
[pageImageNext setAlpha:0];
[pageImage setAlpha:1];
[pageImageBack setAlpha:1];
NSString *imageExtension = #".jpg";
NSString *audioExtension = #".wav";
if (activePage == thePages.count/3)
{
activePage = 1;
}
else
{
activePage = activePage + 1;
}
NSInteger row = 0;
if(activePage == 0)
{
row = activePage;
}
else
{
row = ((activePage) * 3);
}
[leftButton setAlpha:1];
pageImageBack.image = [UIImage imageNamed:[NSString stringWithFormat:#"%#%#", [thePages objectAtIndex:row+0], imageExtension]];
pageImage.image = [UIImage imageNamed:[NSString stringWithFormat:#"%#%#", [thePages objectAtIndex:row+1], imageExtension]];
pageImageNext.image = [UIImage imageNamed:[NSString stringWithFormat:#"%#%#", [thePages objectAtIndex:row+2], imageExtension]];
[UIImageView beginAnimations:NULL context:NULL];
[UIImageView setAnimationDuration:.5]; // you can set this to whatever you like
/* put animations to be executed here, for example: */
[leftButton setAlpha:0];
[rightButton setAlpha:0];
[leftButton setAlpha:1];
[rightButton setAlpha:1];
leftButton.hidden = NO;
/* end animations to be executed */
[UIImageView commitAnimations]; // execute the animations listed above
[imageExtension release];
}
The NSArray is loaded in this action, which is called in the ViewDidLoad:
-(void)loadPages
{
thePages = [[NSArray alloc] initWithObjects:
// How many stacked images do we need to get fade in and outs? Also add column fo
#"page0",#"page0",#"page1",
#"page0",#"page1",#"page2",
#"page1",#"page2",#"page3",
#"page2",#"page3",#"page4",
#"page3",#"page4",#"page5",
#"page4",#"page5",#"page6",
#"page5",#"page6",#"page7",
#"page6",#"page7",#"page8",
#"page7",#"page8",#"page9",
#"page8",#"page9",#"page10",
#"page9",#"page10",#"page11",
#"page10",#"page11",#"page12",
#"page11",#"page12",#"page13",
#"page12",#"page13",#"page14",
#"page13",#"page14",#"page15",
#"page14",#"page15",#"page16",
#"page15",#"page16",#"page17",
#"page16",#"page17",#"page18",
#"page17",#"page18",#"page19",
#"page18",#"page19",#"page20",
#"page19",#"page20",#"page21",
#"page20",#"page21",#"page22",
#"page21",#"page22",#"page23",
#"page22",#"page23",#"page24",
#"page23",#"page24",#"page25",
#"page24",#"page25",#"page26",
#"page25",#"page26",#"page27",
#"page26",#"page27",#"page27",
nil];
}
It all works just fine until about the 10-12th page when I start to get memory warnings in the console and usually a crash.
I am pretty sure it is just a matter of releasing the three large UIImageViews at the right time, but I can't figure out when...I've tried a number of different spots in the code.
I was doing an app like this, where I had a lot of image views and labels that the user could change. I got warnings and crashes all the time. The only thing that seemed to fix it all was to make them all properties. Everything I wanted to hang on to on a certain view I had to make a property. That took care of it nicely, otherwise it seemed like the OS freaked out that I had to much allocated, and would send memory warnings which would release stuff, and then when the app tried to access them it would crash. See if making your pageImageNext, pageImage , pageImageBack properties works.
Make sure you are doing a [thePages release]]; in the dealloc method of the view controller. Not releasing that will definitely cause memory issues.
Also have you made the imageviews retained properties in the view controller? If so, you need to release them in the dealloc as well.
As for memory warnings, you can unset the imageviews in didRecieveMemoryWarning and then just add in a check to re-create them as needed.
The code:
[imageExtension release];
Is incorrect and should be deleted. "imageExtension" is allocated on the stack, and will go away when the method exits. Only release things that you have alloc'd.
Do you have just one of these types of ViewControllers? Or one for each page?
#sasquatch #YuzaKen #MishieMoo If I simply set self.pageImage = nil; in the dealloc, as you suggested, won't that only release the memory when a user leaves the ViewController?
I feel like I need to be releasing the UIImageViews as I move down the rows of the array, when I replace the contents of the UIImageView with a new image, no?

removeFromSuperview for some reason replaces object with UIImageView?

I have been through every single thing allocated in my code and given it a tag of -1, except from the Icons, which use up the tag system. So here's my code:
NSLog(#" 1: %#", (Icon *)[self viewWithTag:index]);
Icon *icon = (Icon *)[self viewWithTag:index];
CGRect frame = icon.frame;
[icon removeFromSuperview];
icon = nil;
Icon *icon2 = [[Icon alloc] init];
[icon2 makeIconStandardWithTag:(int)index];
icon2.frame = frame;
[self addSubview:icon2];
NSLog(#" 2: %#", (Icon *)[self viewWithTag:index]);
NSLog 1 returns the object to be an icon. NSLog 2 returns the object to be a UIImageView, despite me searching my code thoroughly for every UIImageView and giving it a -1 tag. Through moving NSLog 2 around, i've discovered that the line [icon removeFromSuperview]; is the problem here. If that line isn't included, it doesn't happen. But obviously i need to remove it from superview and .alpha = 0is too much of a patch-over fix.
What value are you using for the tag? Sometimes I have troubles if I use a value that's too low (I assume because UIKit is using that tag value).
Try setting index to some random large number.
Also, why not just use an instance variable to refer to the Icon? Then you won't have to mess around with identifying the icon by its tag.

How can I see the intermediate updates on my UI while debugging iPad code?

I am developing an app in which I am using a plist file. There are 21 key-value pairs in the plist. Each pair is a dictionary (type) with 6 items. The dictionary contains a set of images. In my program, I am using the path to retrieve the images. My requirement is that the images should be displayed one-by-one on the imageView. i have done it successfully. The images are being dispalyed exactly from plist.
So my question is can I use the debugger to see the intermediate execution of the plist? When I placed breakpoints in my code, and run using the debugger, I am able to step into the code and the images are displayed on the view only after the whole execution of plist with 21 key-value pairs is done. How can I see the images on the view while debugging each pair?
(void)setSequenceInfo:(NSDictionary *)sequenceInfo
{
[self.subviews makeObjectsPerformSelector:#selector(removeFromSuperview)];
self.sequenceQueue = [NSMutableArray array];
//load the sequenceinfo dictionary
[_sequenceInfo release];
if (!sequenceInfo)
return;
_sequenceInfo = [sequenceInfo retain];
//create one UIImageView by sequence
NSMutableDictionary* views = [NSMutableDictionary dictionaryWithCapacity:[sequenceInfo count]];
for (NSString* identifier in _sequenceInfo)
{
UIImageView* seqView = [[UIImageView alloc] initWithFrame:self.bounds];
seqView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
seqView.contentMode = self.contentMode;
//the image is hidden until its sequence is played
seqView.hidden=YES;
//add the newly created image view to our subviews
[self addSubview:seqView];
//also store it in our sequenceViews dictionary
[views setValue:seqView forKey:identifier];
[seqView release];
}
self.sequenceViews = views;
}
In order to "see" intermediate results while using the debugger, you'll have to change the structure of your code to return to the main run loop, so that the UIImageView has the chance to run and display the new image. You could set up a timer that fires periodically, and in the timer routine you change the UIImageView's image to the next one in the sequence. Then you set your breakpoint in the timer handler method in gdb, and when you hit that breakpoint each time you should see the previously displayed image.
EDIT: here's some more detail, based on what I think you want to do. Realize, though, that I think there's no "magic wand" to be able to see changes on the screen while you're in the debugger. You have to return to the Run Loop so that your UIKIt widgets get cycles to draw themselves.
For example, say you have this method:
- (void) updateTwoLabels:(NSString *)newText
{
self.label1.text = newText;
self.label2.text = newText; // put breakpoint on this line
}
and you want to stop in the debugger just before label2's text is set, and see that label1 has changed. Well, I think there's no way of doing that, except by modifying your code, and calling yourself again with performSelector:withObject:afterDelay: so that the main run loop can run for a while then call your code again:
BOOL callAgain = NO;
BOOL setLabel2 = YES;
- (void) updateTwoLabels:(NSString *)newText
{
self.label1.text = newText;
if ( setLabel2 )
self.label2.text = newText; // put breakpoint on this line
if ( callAgain )
[self performSelector:#selector(updateTwoLabels:) withObject:newText afterDelay:0];
}
in this way, when you're debugging, you can set callAgain to YES and setLabel2 to NO in gdbg, and keep "continuing" until you see that label1 has changed. That's the basic technique.
Do the whole method in a background thread but call GUI stuff on the main thread. For example: [self performSelectorOnMainThread:#selector(addSubview:) withObject:seqView waitUntilDone:YES]. Don't forget to make an autorelease pool at the beginning of the method (the one that runs in the background thread) and drain it at the end of it.

Problem releasing object using "removeFromSuperView" iPhone

I have this concrete problem, but if You find my initial design idea crazy and have a better suggestion, please let me know:)
I have a UIView that acts as a container/background for adding other views. The important thing is that only one view is present at a time. So before doing any adding of views I do this:
for(UIView *v in [self.currentView subviews]) {
[v removeFromSuperview];
}
self.currentView is the view I add my subviews to.
After this I add a new UIView in this manner:
UIView *tempView;
switch (self.currentIndex) {
case 1:
tempView = [[AView alloc] initWithFrame:frame];
[self.currentView addSubview:tempView];
[tempView release];
break;
case 2:
tempView = [[AView alloc] initWithFrame:frame];
[self.currentView addSubview:tempView];
[tempView release];
break;
default:
break;
}
This way I remove all views, since I release the tempView straight after I add it to
the self.currentView I end up with a retain count of one on the the UIView currently living
in the currentView.
This all seems fine, but as I look at it with Instruments I can see that each time I run the above code a new AView object is allocated and the old one keeps hanging around with a retain count of 1, either I am missing some obvious retain action being performed on my object or else the "removeFromSuperView" does not call "release" on my view.
In real life my objects are not of type AView, but of many different types, but this way I can test if there is always only one AView instance allocated.
As I can read from the documentation "removeFromSuperView" should call "release" on the view so I am a bit confused as to why my Views are not deallocated.
Again, maybe I am going about this the wrong way and suggestions are really welcome.
The setup is that there is a number of button at the bottom of the screen and when the user clicks on the view changes.
Thanks for any help or pointers given:)
You are iterating a collection and simultaneously changing it
Try
while ([self.currentView subviews].count>0) {
[[[self.currentView subviews] objectAtIndex:0] removeFromSuperView];
}
instead.
you could try the "bringSubviewToFront" and "sendSubviewToBack" functions instead of creating a new UIView everytime. That ways, you won't be creating uiviews for every action and therefore be less pressing on the memory consumption of your application.