创建一个全球课堂目标-C? [英] creating a global class objective-c?
本文介绍了创建一个全球课堂目标-C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用已经存储的数据在objective-c中创建一个类,以便访问数据时我不想实例化类。我怎么做到这一点?
I want to create a class in objective-c with already stored data, so that for accessing the data I don't want to instantiate the class. how can I do it?
推荐答案
你可以使用单例,或者你可以使用仅由类方法构成的类并给你访问静态数据。
You can use a singleton or you can use a class made only of class methods and giving you access to static data.
以下是ObjC中的一个基本单例实现:
Here is a basic singleton implementation in ObjC:
@interface MySingleton : NSObject
{
}
+ (MySingleton *)sharedSingleton;
@property(nonatomic) int prop;
-(void)method;
@end
@implementation MySingleton
@synthesize prop;
+ (MySingleton *)sharedSingleton
{
static MySingleton *sharedSingleton;
@synchronized(self)
{
if (!sharedSingleton)
sharedSingleton = [[MySingleton alloc] init];
return sharedSingleton;
}
}
-(void)method {
}
@end
您可以像这样使用它:
and you use it like this:
int a = [MySingleton sharedSingleton].prop
[[MySingleton sharedSingleton] method];
基于类的方法类为:
The class method based class would be:
@interface MyGlobalClass : NSObject
+ (int)data;
@end
@implementation MySingleton
static int data = 0;
+ (int)data
{
return data;
}
+ (void)setData:(int)d
{
data = d;
}
@end
这篇关于创建一个全球课堂目标-C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文