dealloc中的自定义UIButton内存管理

dia*_*ich 1 iphone memory-management uibutton dealloc ios

我希望澄清这里发生的过程.

我创建了一个UIButton的子类,其init方法如下所示:

- (id)initWithTitle:(NSString *)title frame:(CGRect)btnFrame {
    self = [UIButton buttonWithType:UIButtonTypeCustom];
    [self setTitle:title forState:UIControlStateNormal];
    self.frame = btnFrame;
    return self;
}
Run Code Online (Sandbox Code Playgroud)

在我的视图控制器中,我正在创建其中一个按钮并将其添加为子视图:

myButton = [[CustomButton alloc] initWithTitle:@"Title" frame:someFrame];
[self.view addSubview:myButton];
Run Code Online (Sandbox Code Playgroud)

在视图控制器的dealloc方法中,我记录了我的按钮的保留计数:

- (void)dealloc {
    NSLog(@"RC: %d", [myButton retainCount]); //RC = 2
    [super dealloc];
    NSLog(@"RC: %d", [myButton retainCount]); //RC = 1
}
Run Code Online (Sandbox Code Playgroud)

我理解它的方式,myButton实际上并没有保留,即使我使用它调用它alloc,因为在我的子类中我创建了一个自动释放按钮(使用buttonWithType:).

在dealloc,这是否意味着,当调用dealloc时,superview会释放按钮,其保留计数会降至1?该按钮尚未自动释放?

或者我需要在调用[super dealloc]后将保留计数降为零?

干杯.

bbu*_*bum 5

这应该得到两个答案......一个用于特定问题,一个用于在-init(此一个)中替换实例时如何管理内存.

初始化器在Objective-C内存管理领域是一个奇怪的鸟.实际上,你正在管理self.入境时,self保留.退出时,你有望重返无论是一个保留的对象-并不一定是同一个对象self- 或 nil.

所以,打破[[[Foo alloc] init] autorelease]下来的标准习语:

id x = [Foo alloc]; // allocates instance with RC +1
x = [x init]; // RC is preserved, but x may differ
[x autorelease]; // RC -1 (sometime in future)
Run Code Online (Sandbox Code Playgroud)

请注意,所有保留计数[RC]都表示为增量.

因此,在该init方法中,您通常不会更改保留计数self!

但是,如果你想返回一些其他对象,你需要release self 和 retain你要返回的任何东西(无论是当时分配还是先前在其他地方分配,比如从缓存中检索对象时).

具体来说,由于这个答案过于迂腐,一切都被吹成了个别表达:

- init {
    [self release];
    self = nil;
    id newObject = [SomeClass alloc];
    newObject = [newObject init];
    if (newObject) {
        self = newObject;
        ... initialize self here, if that is your fancy ...
    }
    return self;
}
Run Code Online (Sandbox Code Playgroud)