需要帮助才能找到适用于iOS的简单Objective-C代码中的错误

时间:2014-08-03 21:03:32

标签: ios objective-c

我是Obj-C编程的新手,我无法在代码中找出问题。 下面我粘贴了来自不同类的代码... 当我运行我的应用程序时,_pirate.health的值为零,_pirate.weapon.damage的值为零,_pirate.weapon.name的值为(null)

我不知道它为什么不起作用。我现在非常绝望:( 我将感激你的帮助!

ViewController.h

@property (strong, nonatomic) NCharacter *pirate;

ViewContoller.m

_pirate.health = 100;
_pirate.weapon.damage = 10;
_pirate.weapon.name = @"Fist";

Character.h

@property (strong, nonatomic) NWeapon *weapon;
@property (nonatomic) int health;

Character.m

@implementation NCharacter

- (instancetype)init
{
    self = [super init];
    if (self) {
        _weapon = [[NWeapon alloc] init];
    }
    return self;
}

@end

NWeapon.h

@property (strong, nonatomic) NSString *name;
@property (nonatomic) int damage;

NWeapon.m

@implementation NWeapon
- (instancetype)init
{
    self = [super init];
    if (self) {
        _name= [[NSString alloc] init];
    }
    return self;
}
@end

1 个答案:

答案 0 :(得分:2)

您似乎永远不会分配属性self.pirate - 在头文件中分配属性并不会自动为您创建对象。因此,在调用NCharacter方法之前,您需要alloc] init];

试试这个:

_pirate = [[NCharacter alloc] init];
_pirate.health = 100;
_pirate.weapon.damage = 10;
_pirate.weapon.name = @"Fist";

在某些情况下,它对延迟加载属性很有用。 Todo在您的ViewController.m中创建以下内容:

-(NCharacter *)pirate
{
    if(!_pirate){
        _pirate = [[NCharacter alloc] init];
    }

    return _pirate;
}

因此,您将能够使用类似于之前的内容

self.pirate.health = 100;
self.pirate.weapon.damage = 10;
self.pirate.weapon.name = @"Fist";

self.pirate的调用将为您实例化对象。

相关问题