Problem releasing object using "removeFromSuperView" iPhone - 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.

Related

iOS: Removing one view from superview causes another to get removed?

This is a very odd problem. I have 5 subviews added to a UIViewController. One of them needs to be removed, but when I do this, one of the remaining 4 subviews is also removed. This necessitates that I re-add it using addSubview. The two views in question are not related in any way.
Is this a known iOS SDK bug? It happens for sure running on the simulator with iOS 6.1.
Thanks.
Here, In Your Question not mention That which Method you use for remove subView so,I give you simple suggestion for remove subView.
Give Tag of Each subView such like,
self.subView1.tag = 1;
self.subView2.tag = 2;
.
.
.
.
self.subViewN.tag = N;
And You can access(Remove) any subView base on its Tag, such like
[[self.view viewWithTag:1] removeFromSuperview];
This tips might helpful for you.
You can remove single subview using the following code.
[subview_Name removeFromSuperview];
if you want to remove all subviews form the view then use this.
NSArray *subViewArray = [self.view subviews];
for (id obj in subViewArray)
{
[obj removeFromSuperview];
}
if you want to remove all subview of particular class then use this.
NSArray *subViewArray = [self.view subviews];
for (id obj in subViewArray)
{
if([obj isKindOfClass:[classname class]])
{
[obj removeFromSuperview];
}
}
example : if you want to remove subview of UIImageView class then replace if condition with this.
[obj isKindOfClass:[UIImageView class]]

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?

How do i properly discard a subview?

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.

iPhone loading view from nib only works once

I'm trying to add a «loader-view» to my app which shows a spinner while doing stuff.
This works fine the first time, but it doesn't work a second time.
here's what I do:
I have a viewController for the spinner (spinnerViewController) and a nib-file which I made in IB (spinner.xib).
I load the nib in the viewDidLoad-event:
spinnerView = [[spinnerViewController alloc] initWithNibName:#"spinner" bundle:nil];
[spinnerView retain];
spinnerView is declared in the .h-file (spinnerViewController *spinnerView;)
next, I show the spinner-view:
[self.view addSubview:spinnerView.view];
[self.view bringSubviewToFront:spinnerView.view];
which works fine...
And now the trouble starts. No matter what I do, I can't show the spinner view again.
I tried just hiding it (self.view sendSubViewToBack: spinnerView.view) which works for hiding, but when I try to bring it to the front again (self.view bringSubViewToFront: spinnerView.view) it doesn't work.
I also tried removing the spinner-view and add it again with no success (within the spinnerViewController: [self.view removeFromSuperview] and to show it again [self.view addSubview... )
[EDIT]
I changed the whole setup a little and just made the spinner-view a subview in IB - again, hiding works, but showing again fails.
What I found out: After the bringSubViewToFront-command, I call some web-service to get some data. When I comment the following code out and just show the spinnerView, it works. So now I'm trying to figure out how to determine when the spinner-view appeared and then continue with the code - but naturally, this doesn't work (yet) :)
Any ideas what I'm doing wrong??? ;)
Problem solved.
This page gave the answer: http://urenjoy.blogspot.com/2009/05/uiactivityindicatorview.html
Apparently, the update has to happen in a separate thread, as the web-stuff blocks the current one, hence the view did not appear.
[NSThread detachNewThreadSelector:#selector(doWork) toTarget:self withObject:nil];
- (void) doWork {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
.....Time Consuming Code here .....
[pool release];
}
I might be not exactly on your question, but in general creating a ViewController class in order to show a spinner on the screen is a huge overkill ... just try to discover the logic behind what you do : you create a viewcontroller, but you never use it, you use the view.
So in short I believe you need only a UIView (the view property of the UIViewController)
Why don't you try something like :
... in your class interface...
UIActivityIndicator* activity;
... when the activity needs to happen ...
activity = [[UIActivityIndicator alloc] initWithActivityIndicatorStyle: ....
[activity startAnimating];
[self.view addSubview:activity];
[activity release]
... when the activity is finished
[activity removeFromSuperview]; //this will also decrease the retain count

How to change the UIImage of a UIImageView from a subview?

I want to change an image on a view, from a popup dialog of 4-6 icons (imagine like changing your image on a messenger application).
The way I implement this modal popup is by creating a new view at IB, with opacity on the background, and then I load this as a subview:
IconsViewController *iconsViewController = [[IconsViewController alloc] initWithNibName:#"IconsView" bundle:nil];
[self.view addSubview:iconsViewController.view];
So, when the user touches an icon, I have
- (IBAction)iconIsSelected:(id)sender {
switch ([sender tag]) {
case 1:
[(ParentViewController*)[self superview] changeIcon];
break;
case 2:
// same here..
break;
default:
break;
}
[self.view removeFromSuperview];
[self release];
}
The changeIcon just sets the image to a corresponding icon.
As you can guess, this is not working - the changeIcon message never works.
I can't understand what am I doing wrong, any help much appreciated!
You have a few choices here...
First one is create a property on your IconsViewController of type ParentViewController*, for example:
#property (readwrite,nonatomic,assign) ParentViewController* parentController; // weak reference
To break this down further:
readwrite because we want to be able to access the value via [self parentController] but also change it via [iconsViewController setParentController:self]
nonatomic because I'm not too worried about threading
assign to make it a "weak reference" where the parent will not be retained by the child. If they each retain the other, it could lead to memory leaks later because unless explicitly released you'd end up with a retain circle causing neither object to hit a zero retain count.
When you load from nib, set the property:
IconsViewController *iconsViewController = [[IconsViewController alloc] initWithNibName:#"IconsView" bundle:nil];
iconsViewController.parentController = self;
Then, call to it from inside of iconIsSelected like this:
[[self parentController] changeIcon];
Alternatively, you can create a delegate protocol:
#protocol IconViewSelectedDelegate (NSObject)
- (void) changeIcon;
#end
And use that protocol as a property, instead of the parent view controller type. This is more abstract, but it keeps the design cleaner. The parent view controller would then implement that delegate protocol, as one of many others.
Another option is to use NSNotificationCenter and publish/subscribe to events from your dynamic view. This is the "loosest" coupling between the two objects, but it might be overkill for this scenario.
The superview of a view is a view, not a view controller, yet you cast the superview to be of class ParentViewController. If the view has no superview, it returns nil, and message to nil are no-ops (which explains why you don't crash there).
BTW, that [self release] at the end is highly suspicious.