简体   繁体   中英

Objective-C keep track of my view in subviews array

I have a question about memory management. For example I have an iPhone application that uses multiply programmatically created views. for example programmatically generated buttons.

    UIButton *myButton=[UIButton alloc] initWithFrame:...; //etc

then, normally we add this button to subviews array:

    [self.view addSubview:myButton];

then we releasing button.

    [myButton release]

When I need to remove this button how can I keep track on this button in subviews array? I know I can do this using tag property but I think exists another way to keep connection with it.

You can simply assign it to an instance variable:

UIButton *myButton = ...;
[self.view addSubView:myButton];
myInstanceVariable = myButton;
[myButton release];

You just need to be careful: as soon as you do something like [myInstanceVariable removeFromSuperview]; it might get deallocated immediately (if you haven't retained it) and it would then point to invalid memory.

You can try to declare somewhere a retain property of UIButton* type, that can be assigned with pointer value to your button instance:

@interface myclass
@property (retain, nonatomic) UIButton *savedButton;
@end

@implementation myclass
@synthesize savedButton;

- (void) someMethod...
{
  ...
  UIButton *myButton=[UIButton alloc] initWithFrame:...;
  [self.view addSubview:myButton];
  self.savedButton = myButton;
  [myButton release];
  ...
}
...
@end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM