2012-03-08 41 views
0

我想声明的是可以通过在类中的任何方法来访问一个UInt32的变量UInt32的变量..如何声明与全球级接入

所以其全球的类中的方法,但没有任何其他类别。 ..

我试图做这样的.H

@interface EngineRequests : NSObject { 

    UInt32 dataVersion; 
} 

@property (copy) UInt32 dataVersion; 

但那不是工作..我得到就行了@property等错误..我甚至需要一个或者仅仅使用顶部的UInt32就可以。

回答

1

你可以尝试

@interface EngineRequests : NSObject { 
@protected 
    UInt32 dataVersion; 
} 

@property (assign) UInt32 dataVersion; 
@end 

@implementation EngineRequests 

@synthesize dataVersion; 

// methods can access self.dataVersion 

@end 

但你并不真正需要的属性,除非要授予外部访问/控制。您可以在类接口中声明UInt32 dataVersion,然后在没有self.的实现中参考dataVersion。无论哪种方式,@protected都将阻止外部类直接访问dataVersion

您是否阅读过Objective-C Properties

初始化

EngineRequestsNSObject一个子类。因此,你可以(一般应该)覆盖的NSObject-(id)init方法,像这样:

-(id)init { 
    self = [super init]; 
    if (self != nil) { 
     self.dataVersion = 8675309; // omit 'self.' if you have no '@property' 
    } 
    return self; 
} 

或者创建自己的-(id)initWithVersion:(UInt32)version;

+0

完美的工作,说如果我有一个方法是通过参数初始化该UInt32 var,我该怎么做? 我试过这个** - (void)initalizePacketVariables:(UInt32) {//...** 但是,这会导致错误.. – 2012-03-08 02:37:39

+0

已添加更新。您在评论中描述的方法也可以正常工作。 'init'是Cocoa的最佳实践。 – QED 2012-03-08 02:44:01

+0

好凉爽..我会尽力并把它全部弄清楚。感谢您的帮助 – 2012-03-08 02:48:25

0

您只需在接口中声明该变量以使其对所有类方法都可见。使用@property ....创建getter-setter将使其成为类变量,并且它将在类之外可见。你必须这样做。

@interface EngineRequests:NSObject的{

UInt32 dataVersion; 

}

罢了。