是什么区别使用" _predictions"和#34; self.predictions"?

时间:2014-04-14 23:19:27

标签: ios objective-c

按照Treehouse教程,应用程序应该访问一个字符串数组,并在按下按钮后随机返回一个字符串。我认为“_predictions”和“self.predictions”是一回事。当我在NSString“randomPrediction”的实现中将所有“self.predictions”更改为“_predictions”时,没有返回任何内容。使用“self.predictions”和“_predictions”有什么区别?

#import "SLWCrystallBall.h"

@implementation SLWCrystallBall

- (NSArray *) predictions {
    if (_predictions == nil) {
        NSLog(@"NBA team names accessed");
        _predictions = [[NSArray alloc] initWithObjects:
            @"The Oklahoma City Thunder", @"The San Antonio Spurs", @"The Miami Heat", 
            @"The Indiana Pacers", @"The Chicago Bulls", @"The Toronto Bulls", 
            @"The Boston Celtics", @"The Brooklyn Nets", @"The New York Knicks", 
            @"The Philadelphia 76ers", @"The Cleveland Cavaliers", @"The Detroit Pistons", 
            @"The Milwaukee Bucks", @"The Atlanta Hawks", @"The Charlotte Bobcats", 
            @"The Orlando Magic", @"The Washington Wizards", @"The Denver Nuggets", 
            @"The Minnesota Timberwolves", @"The Portland Trail Blazers", 
            @"The Utah Jazz", @"The Golden State Warriors", @"The Los Angeles Clippers", 
            @"The Los Angeles Lakers", @"The Phoenix Suns", @"The Sacramento Kings", 
            @"The Dallas Mavericks", @"The Houston Rockets", @"The Memphis Grizzlies", 
            @"The New Orleans Pelicans", nil];

    }
    NSLog(@"Team name returned");
    return _predictions;
}

- (NSString*) randomPrediction {
    int random = arc4random_uniform((uint32_t)self.predictions.count);
    return [self.predictions objectAtIndex:random];
    NSLog(@"Random prediction created");
}

@end

这是头文件:

#import <Foundation/Foundation.h>

@interface SLWCrystallBall : NSObject {
    NSArray *_predictions;
}

@property (strong, nonatomic, readonly) NSArray *predictions;

- (NSString*) randomPrediction;


@end

1 个答案:

答案 0 :(得分:2)

_predictions直接访问变量,而self.predictions则调用访问者。由于内存管理的好处,您应该使用self.predictions。在您的情况下,访问者创建数组,因此它几乎是必要的。请注意,在-predictions方法中,您必须使用_predictions,否则您的访问者只会自行调用。