2013-08-25 63 views
0

我無法從另一個類訪問int屬性。我知道這個問題已經被問了好幾次了,但是在之前的問題中沒有任何解決方案似乎可行。我在xcode方面的知識是基本的,我正在使用這個項目來發展我的技能。從另一個類訪問int值

我有兩個類:HelloWorldLayer和ClassOne。 ClassOne指出int的值。兩者都是Cocos2d CCLayer類(可能不是實踐類間價值訪問的最佳類)。

ClassOne.h

@interface ClassOne : CCLayer { 
    int ageClass; 
} 
@property (nonatomic, readwrite)int ageClass; 

@end 

ClassOne.m

@implementation ClassOne 
@synthesize ageClass = _ageClass; 

-(id)init{ 
    if((self=[super init])){ 
    _ageClass = 10; 

    } 
return self; 
} 

@end 

HelloWorldLayer.h

#import "ClassOne.h" 

@interface HelloWorldLayer : CCLayer <...> { 
    ClassOne *agePointer; 
} 
@property (nonatomic,assign)ClassOne *agePointer; 
+(CCScene*)scene; 

@end 

HelloWorldLayer.m

#import "HelloWorldLayer.h" 
#import "AppDelegate.h" 
#import "ClassOne.h" 

@implementation HelloWorldLayer 
@synthesize agePointer = _agePointer; 
+(CCScene*)scene... 

-(id)init{ 
    if((self=[super init])){ 
    _agePointer.ageClass = self; 

    NSLog(@"ClassOne int = %@",_agePointer); 

    } 
return self; 
} 

... 
@end 

輸出結果:

"ClassOne int = (null)" 

or "0" if i use "%d" token and "int = x", where the line "int x =_agePointer.ageClass;" 
is used. 

我後的結果是對HelloWorldLayer NSLog的顯示 「10」,在ClassOne定義的int值。

我非常感謝我對語言使用的任何智慧和修正。

+0

請問這個線的裝置「_agePointer.ageClass = self;」 ageClass是一個整數,您嘗試在其中分配一個對象。我認爲它會工作如下: - (id)init if((self = [super init])){{}} {{ClassOne alloc] init]; NSLog(@「ClassOne int =%d」,_ agePointer.ageClass); } return self; } –

+0

我正在使用這個問題作爲指導[鏈接](http://stackoverflow.com/questions/9371125/accessing-a-value-of-a-classs-variable-from-another-objective-c)。我的印象是,該行將「ageClass」的值賦給「_agePointer」。 –

+1

解決了它。謝謝Prateek,如果你把它作爲答案發布,我會接受它。 –

回答

0

好試試這個:

-(id)init 
{ 
    if((self=[super init])){ 
     _agePointer = [[ClassOne alloc] init]; 
     NSLog(@"ClassOne int = %d",_agePointer.ageClass); 
    } 
    return self; 
} 
0

首先,當輸出int時,在您的NSLog中始終使用%d而不是%@

所有第二,如果你期望輸出10,你應該已經先實例化的類在HelloWorldLayer.m

-(id)init{ 
    if (self = [super init]) { 
    _agePointer = [[ClassOne alloc] init]; 

    NSLog(@"ClassOne int = %@",_agePointer); 
    } 
    return self; 
} 
+0

謝謝恩里科,啓動這個班是絕對需要的。 –