0

私はObjectiveCを初めて使用し、いくつかの非常に基本的なことに問題を抱えています。
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];

クラスから属性を設定および取得する方法は、以前はクラスのプロパティを宣言することでした。このようにして、コンパイラはメモリを管理します(保持および解放)。別の方法は、ivarに直接アクセスすることです。

ただし、setValue:forKeyPath:を使用する場合は、変数の名前である2番目のパラメーターに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

「health」と「attack」を使用して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]];

これら2つは同等です。

于 2012-08-04T21:18:02.790 に答える