为什么NSString返回null?

时间:2014-10-13 21:56:59

标签: objective-c nsstring

#import <Foundation/Foundation.h>

//-----Interface-----

@interface Person: NSObject{

int age;
int weight;
NSString *name;

}

-(void) print;
-(void) setAge: (int) a;
-(void) setWeight: (int) w;
-(void) setName: (NSString*) n;

@end

//-----Implementation-----
@implementation Person

-(void) print{
    NSLog(@"%@ is %i years old and my weight is %i pounds", name, age, weight);
}

-(void) setAge: (int) a{
age=a;
}

-(void) setWeight: (int) w{
weight=w;
}

-(void) setName: (NSString*) n{
name=n;
}

@end

//-----Main Program-----
int main(int argc, const char * argv[]) {

@autoreleasepool {

    Person *james = [[Person alloc]init];
    Person *bob = [[Person alloc]init];

    [james setAge: 55];
    [james setWeight: 400];
    [james print];

    [bob setAge: 80];
    [bob setWeight: 150];
    [bob print];

}

return 0;

}

它应该回归&#34;詹姆斯55岁,我的体重是400磅&#34;并且&#34; bob是80岁,我的体重是150磅&#34;

但不是&#34; bob&#34;和&#34; james&#34;我得到&#34;(null)&#34;

为什么会发生这种情况的任何想法?

2 个答案:

答案 0 :(得分:3)

您实际上并未在代码中的任何位置调用setName;)请尝试:

// ... other code happens here, then:

@autoreleasepool {

    Person *james = [[Person alloc]init];
    Person *bob = [[Person alloc]init];

    [james setAge: 55];
    [james setWeight: 400];
    [james setName: @"james"]; // you need this
    [james print];

    [bob setAge: 80];
    [bob setWeight: 150];
    [bob setName: @"bob"]; // and this
    [bob print];

}

最后,请记住,仅仅因为您创建了具有特定名称的类实例(在本例中为jamesbob),并未明确设置名称等属性。

您可以尝试一些有点聪明的事情,例如在您的类中添加初始化方法:

在标题/界面中:

- (id) initWithName:(NSString*)name;

在您的实施中:

- (id) initWithName:(NSString*)name
{
    self = [super init];
    if (self != nil)
    {
        [self setName:name];
    }
    return self;
}

然后你可以打电话:

Person *james = [[Person alloc]initWithName:@"james"];

答案 1 :(得分:1)

似乎你永远不会调用[james setName:@"james"]这样的内容,因此name属性永远不会被初始化