我有一个自定义类,其中包含用于性别的字符串和用于服务器交互的布尔值。

。H

@interface Member : NSObject
...
@property (nonatomic, strong) NSString *gender;
@property (nonatomic) BOOL isMale;
...

.m
    - (void)setIsMale:(BOOL)isMale
    {
        _isMale = isMale;

        if (isMale) {
            self.gender = @"Male";
        }
        else {
            self.gender = @"Female";
        }
    }

我也想做相反的事情,这意味着当性别更改为女性时,我希望将isMale属性设置为NO。但是,如果也为性别定义一个二传手,那么这两个二传手将处于无限循环中。有没有办法实现两个不会互相循环的 private 设置器?

这将是导致infitine循环的代码
- (void)setGender:(NSString *)gender
{
    _gender = gender;

    if ([gender isEqualToString:@"Male"]) {
        self.isMale = YES;
    }
    else if ([gender isEqualToString:@"Female"]) {
        self.isMale = NO;
    }
    else {
        // discard...
    }
}

最佳答案

第三笑的原理,即“Divide et impera”:

- (void)setIsMale:(BOOL)male
{
    [self setIsMaleInternal:male];
}

- (void)setGender:(NSString *)_gen
{
    if ([_gen isEqualToString:@"male"]) {
        [self setIsMaleInternal:YES];
    } else if ([_gen isEqualToString:@"female"]) {
        [self setIsMaleInternal:NO];
    } else {
        [World burn]; // or just an exception?
    }
}

- (void)setIsMaleInternal:(BOOL)flag
{
    _isMale = flag;
    if (flag) {
        _gender = @"male";
    } else {
        _gender = @"female";
    }
}

10-08 05:23