我对 Objective C 还是很陌生,所以请多多包涵:
我的应用有一个委托(delegate)、一个导航 Controller 和一个 View 。 我还使用 Singleton 作为“全局”变量。
我知道我可以做到,但它看起来很笨拙:
#import "GlobalData.h"
@synthesize ...
NSInteger junk;
NSInteger moreJunk;
-(void)myMethod{
GlobalData *globDat=[GlobalData getSingleton];
junk=globDat.someValue;
}
-(void)myOtherMethod{
GlobalData *globDat=[GlobalData getSingleton];
moreJunk=globDat.someOtherValue;
}
我想这样做,但不能:
#import "GlobalData.h"
@synthesize ...
NSInteger junk;
NSInteger moreJunk;
GlobalData *globDat=[GlobalData getSingleton]; //Compiler won't allow this line
-(void)myMethod{
junk=globDat.someValue;
}
-(void)myOtherMethod{
moreJunk=globDat.someOtherValue;
}
但是我可以这样做:
#import "GlobalData.h"
@synthesize ...
NSInteger junk;
NSInteger moreJunk;
GlobalData *globDat;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
globDat=[GlobalData getSingleton];
}
return self;
}
-(void)myMethod{
junk=globDat.someValue;
}
-(void)myOtherMethod{
moreJunk=globDat.someOtherValue;
}
那么,是否有一种标准/通用/正确的“初始化”方法可用于所有类?
我应该在每个类(class)都这样做吗?
-(id)init{
if(self=[super init]){
globDat=[GlobalData getSingleton];
}
return self;
}
最佳答案
I know I can do this but it seems ungainly...
您似乎在问如何取消从单例中检索所需值的部分。最好的方法是首先消除单例。
您说您有一个应用委托(delegate)、一个导航 Controller 和一个 View 。您可能还有一个 View Controller 。如果这些是您应用程序中的主要对象,您可能会考虑将数据存储在 View Controller 中。或者,将您的单例转换为合法的数据模型,并让您的 View Controller 在属性中保留对它的引用。然后你可以这样说:
-(void)myMethod{
junk = self.model.someValue;
}
这与您似乎要求的非常接近。
关于ios - 为 iOS 7 设置变量值的最佳 'init' 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22616804/