Why can't I retain a UIView-Pointer?
I'm trying to pass a UIView to another class - which kinda works, but I can't retain the pointer...
in my .h file I declare the view:
UIView *someView;
I add the property
@property (nonatomic, retain) UIView *someView;
And in the .m-file I synthesize the property
@synthesize someView;
Then I have a method to set the view (which is set in the .h file as well - believe me :):
-(void)makeViewPointer:(UIView *)myView{
someView = [[UIView alloc] init];
someView = myView;
for(UIView *aView in someView.subviews){
NSLog(@"tag %d", aView.tag);
}
}
So far, everything's working. When I log the someView, I get a pointer and all the subviews are accessable.
I'm calling this method from another class - which seems to work fine.
NOW - I have an IBAction set up to do something with that view after a button is clicked
-(IBAction)doSomething:(id)sender{
NSLog(@"show the view %@", someView);
for(UIView *aView in someView.subviews){ // doesn't output anything
NSLog(@"tag %d", aView.tag);
}
}
At this point, the someView-var is empty again - WHY????
I assumed, that when I use @property (nonatomic, retain), the variable gets 开发者_运维知识库retained automatically?
I also tried to retain the variable upon initializing:
someView = [[UIView alloc] retain];
doesn't work
or
someView = [[UIView alloc] init];
[someView retain];
doesn't work either...
What on earth am I doing wrong???
Thanks for any help!
Few things.
someView = [[UIView alloc] init];
someView = myView;
The above is wrong. First you're creating a new UIView
instance and assigning it to someView
. You then assign myView
to someView
. This is causing a memory leak, because you never released someView
, you just reassigned it.
I think what you're trying to do is this:
[someView release];
someView = [myView retain];
You then have to make sure you release someView
when you're completely finished with it.
This is what the @property (nonatomic, retain)
will do, but to use that you have to do:
[self setSomeView:myView];
If you don't use the self-dot notation then you don't retain the object assigned to the property.
You need to use:
self.someView = myView;
and
for(UIView *aView in self.someView.subviews){
The self notation calls the synthesized accessor methods that manage retention. If you don't use self, nothing is retained properly.
OK - I guess, I did everything as wrong as possible ;)
I should've mentioned, I guess, that I had set up the views in IB. There, I added my class I was talking about, to my parent-view (sounds confusing, I know - but, hey, it's IB :)...
The goal was to have some sort of overlay-view pop up - but I didn't wanted to put that view in a separate nib-file. So, that's why I just added the class from the classes-library.
I finally gave up now and moved the overlay to a separate nib, made my class a view-controller and... everything works fine...
Thanks for the hints anyway, guys - I did learn a good bit...
精彩评论