0

我对Objective C非常陌生,并且在一些非常基本的事情上遇到了麻烦。
AppDelegate.m,我收到以下错误:

使用未声明的标识符“ health
使用未声明的标识符“ attack

代码(分别):

[Troll setValue:100 forKeyPath:health];
[Troll setValue:10 forKeyPath:attack];

我不太确定如何声明标识符。

AppDelegate.m

#import "AppDelegate.h"

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

    NSObject *Troll = [[NSNumber alloc]init];

    [Troll setValue:100 forKeyPath:health];

    [Troll setValue:10 forKeyPath:attack];

    return YES;

}

@end

AppDelegate.h

#import `<UIKit/UIKit.h>`

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@end

@interface Troll : NSObject {

    NSNumber *health;

    NSNumber *attack;

}

@end
4

3 回答 3

4

键是字符串,而不是其他东西(如悬空的语法垃圾)。此外,“100”和“10”不是对象。即使在此之后,您也不想设置类本身的属性,而是设置其实例的属性。尝试

[troll setValue:[NSNumber numberWithInt:100] forKeyPath:@"health"];
[troll setValue:[NSNumber numberWithInt:10] forKeyPath:@"attack"];

反而。

于 2012-08-04T21:18:02.587 回答
1

首先要说的是,你不是在实例化一个 Troll 对象,而是一个 NSNumber……为什么?你必须做Troll *troll = [[[Troll alloc] init] autorelease];

从类中设置和获取属性的方法是在类上声明属性。这样编译器将为您管理内存(保留和释放)。另一种方法是直接访问您的 ivars。

但是,如果您想使用 setValue:forKeyPath: 您必须使用 NSString 作为第二个参数,即变量的名称。

@interface Troll : NSObject
{
    NSNumber *_health;
    NSNumber *_attack;
}

@property (nonatomic, retain) NSNumber *health;
@property (nonatomic, retain) NSNumber *attack;

@end


@implementation Troll

@synthesize health = _health;
@synthesize attack = _attack;

- (void)dealloc
{
    [_health release];
    [_attack release];
    [super release];
}


- (void)customMethod
{
    //using properties
    [self setHealth:[NSNumber numberWithInteger:100];
    [self setAttack:[NSNumber numberWithInteger:5];

    //accessing ivars directly - remember to release old values
    [_health release];
    _health = [[NSNumber numberWithInteger:100] retain];
    [_attack release];
    _attack = [[NSNumber numberWithInteger:5] retain];
}

@end

祝你好运!

于 2012-08-04T21:26:03.393 回答
-1

尽管您正在定义一个名为 Troll 的类,它具有“健康”和“攻击”,但您并没有实例化一个。您可能希望在您的应用程序中使用以下内容之一 didFinishLaunchingWithOptions:

Troll *troll = [[Troll alloc]init];
troll.health = [NSNumber numberWithInt:100];
troll.attack = [NSNumber numberWithInt:10];

或者

Troll *troll = [[Troll alloc]init];
[troll setHealth:[NSNumber numberWithInt:100]];
[troll setAttack:[NSNumber numberWithInt:10]];

这两个是等价的。

于 2012-08-04T21:18:02.790 回答