从另一个类调用getter方法

时间:2013-12-23 17:29:45

标签: ios iphone objective-c uiviewcontroller

当我尝试从另一个类调用getter方法“gender”和“teamName”时(通过创建TeamsViewController类的实例并调用该实例上的方法),这些方法返回null。这是为什么?

感谢您的帮助。

@interface TeamsViewController () {
    NSString *teamName;
    NSString *gender;
}
@end

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    gender = @"boys";
    teamName = @"Basketball";
}

-(NSString *)gender {
    NSLog(@"returning %@",gender);
    return gender;
}
-(NSString *)teamName {
    NSLog(@"returning %@",teamName);
    return teamName;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    if (onBoys==true) {
        gender = @"boys";
    }
    else {
       gender = @"girls";
    }

    [self performSegueWithIdentifier:@"teamsPushSegue" sender:self];
}



TeamsViewController *teamsInstance = [[TeamsViewController alloc]init];     
[teamsInstance gender];

2 个答案:

答案 0 :(得分:5)

使用以下命令创建类的实例:

TeamsViewController *teamsInstance = [[TeamsViewController alloc] init];

不会调用初始化这些实例变量的方法viewDidLoad

而是使用init方法初始化它们:

- (id)init {
    self = [super init];
    if (self) {
        gender = @"boys"; 
        teamName = @"Basketball";
    }
    return self;
}

但是,您可能想要覆盖的方法是initWithNibName:bundle:,您可能希望完全避免调用init方法。

答案 1 :(得分:4)

顺便说一下,您可能希望利用公共属性,而不是自己明确定义实例变量和getter方法。例如:

TeamsViewController.h:

@interface TeamsViewController : UIViewController

@property (nonatomic, copy) NSString *teamName;
@property (nonatomic, copy) NSString *gender;

@end

TeamsViewController.m

// @interface TeamsViewController () {
//     NSString *teamName;
//    NSString *gender;
// }
// @end

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.gender = @"boys";
    self.teamName = @"Basketball";
}

// if you use properties, you don't have to write these methods; they'll be synthesized for you
//
// -(NSString *)gender {
//      NSLog(@"returning %@",gender);
//      return gender;
// }
//
// -(NSString *)teamName {
//     NSLog(@"returning %@",teamName);
//     return teamName;
// }

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    if (onBoys==true) {
        self.gender = @"boys";
    }
    else {
        self.gender = @"girls";
    }

    [self performSegueWithIdentifier:@"teamsPushSegue" sender:self];
}

或者如果这些是私有属性,你可以将属性声明放在​​私有类扩展中(但是我不知道为什么你首先要编写getter方法,如果它们是私有的)。

有关详细信息,请参阅使用Objective-C编程指南的Encapsulating Data部分。