我是iOS开发的新手,我已经完成了单例课程。我理解这个概念,但对实现单例类有疑虑。任何人都可以使用singleton类分享实时示例的源代码。
答案 0 :(得分:1)
这是单身人士班级的GCD的样子。
假设您创建了一个类,MySingleTonClass是NSObject
的子类
MySingleTonClass.h
+(instanceType)sharedManager;
@property (nonatomic, strong) NSString *userName;
MySingleTonClass.m
+(instanceType)sharedManager{
static MySingleTonClass *manager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
manager = [[MySingleTonClass alloc]init];
});
return manager;
}
现在,您可以在ViewController.m
中的其他类中调用此singleTon类。首先导入类
#import MySingleTonClass.h
-(void)viewDidLoad{
MySingleTonClass *manager = [MySingleTonClass sharedManager];
manager.userName = @"ABCDE";
//manager is the singleton Object
}
现在假设您要访问此相同的值。然后假设在ViewController
假设在SecondViewController.m
中 #import "MySingleTonClass.h"
-(void)viewDidLoad{
MySingleTonClass *manager = [MySingleTonClass sharedManager];
NSLog (@"%@",manager.userName);
// This would still log ABCDE, coz you assigned it the class before, So even if you create a new object called manager here, it will return the same Manager you created before.
manager.userName = @"Myname"; //Now the value changed to MyName untill you change it again, in the lifetime of this application.
}
我希望我能让你理解它的概念。
如您所知,dispatch_once_t
是一个GCD片段,它使得其中的代码仅在每个应用程序运行时调用ONCE。您在其中编写的任何代码都将在正在激活的应用程序的生命周期中运行,或者仅调用一次。
答案 1 :(得分:0)
查看原始来源的此链接 - http://getsetgames.com/2009/08/30/the-objective-c-singleton/
{{1}}
答案 2 :(得分:0)
{{1}}
答案 3 :(得分:0)
There are two ways:-
1) We can create singleton class using **GCD** dispatch_once
in this only one object will create if existing object is there then it will refer to them.
+(id)sharedManager
{
static MyManager *sharedMyManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedMyManager = [[self alloc] init];
});
return sharedMyManager;
}
2) Second way is follows:-
+ (id)sharedManager {
static MyManager *sharedMyManager = nil;
@synchronized(self) {
if (sharedMyManager == nil)
sharedMyManager = [[self alloc] init];
}
return sharedMyManager;
}
suppose this above method is written in class **MyManager** then u can use that as follow
MyManager *sharedManager = [MyManager sharedManager];
hope this will help u.