2012-08-04 132 views
0

我對Objective C非常陌生,並且遇到了一些非常基本的問題。
AppDelegate.m,我發現了以下錯誤:在目標C中使用未聲明的標識符

使用未聲明的標識符 '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

鍵是字符串,而不是其他的東西(像晃來晃去的句法垃圾)。此外,'100'和'10'不是對象。即使在此之後,您也不想設置類本身的屬性,而是要設置其實例的屬性。嘗試

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

改爲。

+0

有了這個,我得到了「隱式轉換'int'到'id'不允許使用ARC」 – WorkForPizza 2012-08-04 21:20:58

+0

@WorkForPizza啊我明白了。但那不是我的錯,你的原始代碼是錯誤的。 – 2012-08-04 21:23:29

+0

@WorkForPizza那是因爲你傳遞了一個標量類型(在你的情況下是整數值'100'和'10')而不是一個對象 – JustSid 2012-08-04 21:23:36

-1

儘管您正在定義一個名爲「健康」和「攻擊」的類Troll,但您並未實例化一個類。你可能想在你的應用程序didFinishLaunchingWithOptions下列之一:

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

OR

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

這兩個是等價的。

+0

nononononoooooo!這是編譯器錯誤,而不是運行時錯誤。無關和無關。 -1。 – 2012-08-04 21:18:51

+0

那麼你仍然需要分配和初始化一個Troll對象而不是NSNumber。 – AW101 2012-08-04 21:22:39

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 

祝你好運!