@property的自定义设置器?

Ale*_*lex 13 iphone objective-c ios

合成后如何使用自定义setter作为以下属性?

@property (nonatomic,retain) UIButton *but 
Run Code Online (Sandbox Code Playgroud)

dea*_*rne 23

@Sascha几乎是正确的,但他的代码中有一个小错误;)

它看起来像是:

一个)

-(void)setBut:(UIButton *)value {
    if (but != value) {
        [but release];
        but = [value retain];
    }
}
Run Code Online (Sandbox Code Playgroud)

或B)

-(void)setBut:(UIButton *)value {
    [but autorelease];
    but = [value retain];
}
Run Code Online (Sandbox Code Playgroud)

(A)(非常)效率稍高,(B)更具可读性.


为什么我们需要选项(A)中的if语句而不仅仅是@ Sascha的答案中的释放和保留?

如果两次传入同一个对象会发生什么?

// We set our button for the first time
UIButton *test = [UIButton alloc] init];
[self setBut:test];
[test release];


// Much later in the code, we set the button again
[self setBut:test];
Run Code Online (Sandbox Code Playgroud)

如果我们没有检查那but不是一个不同的对象,那么我们在setter中要做的第一件事就是release它.然后我们将尝试retain一个不再存在的对象,导致崩溃.

注意我们不需要选项(B)中的if语句,因为autorelease不会立即释放按钮,所以我们有时间再次保留它而不会被dealloc'd.


and*_*azz 22

@property (getter=yourGetter,setter=yourSetter:) UIButton *but;
Run Code Online (Sandbox Code Playgroud)