iOS self.xx 和_xx的区别

一般情况下我习惯的是用self.xx,这次在做换肤功能的时候,上网看了些案例,然后copy了一些功能,其中有用到_xx的,刚开始做的时候没啥问题,等到功能做的差不多了,正在测试的时候,发现总有个情况,换肤会有问题。debug的时候,看到的结果和我想的结果不一样。_xx获取到的是nil。

self.xx会调用xx的setter/getter方法,访问的是属性;

_xx是成员变量。

- (BOOL)changeTheme:(NSString *)themeName{
    /** 判断当前切换主题是否在主题数组中*/
    if (![_themeArray containsObject:themeName]) {
        self.defaultSkin = @"default";
        [self sendChangeThemeNotification];
        return YES;
    }
    return NO;
}

- (void)setupThemeNameArray:(NSArray *)array{
    self.themeArray = array;
    
    if (!self.themeArray) {
        self.themeArray = [@[] copy];
    }
    NSString *path = [NSString stringWithFormat:@"%@/themeArray.archive",[CPFileManager skinsDir]];
    [NSKeyedArchiver archiveRootObject:self.themeArray toFile:path];
}

- (NSArray *)themeArray {
    if (!_themeArray) {
        NSString *path = [NSString stringWithFormat:@"%@/themeArray.archive",[CPFileManager skinsDir]];
        NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
        _themeArray = [array copy];
        if (!_themeArray) {
            _themeArray = [NSArray array];
        }
    }
    return _themeArray;
}

这种情况下,如果我退出程序重新进入的话,_themeArray就是为nil。这时候成员变量都没有赋值,需要先访问属性,在get方法里获取到了相应的值才行。所以上面的第一个函数里的_themeArray应该该为self.themeArray。

- (BOOL)changeTheme:(NSString *)themeName{
    /** 判断当前切换主题是否在主题数组中*/
    if (![self.themeArray containsObject:themeName]) {
        self.defaultSkin = @"default";
        [self sendChangeThemeNotification];
        return YES;
    } 
    return NO;
}

猜你喜欢

转载自blog.csdn.net/jdd92/article/details/124497088
xx
今日推荐