Common Objective-C Patterns(Chapter 4 of Objective-C Phrasebook)

本文详细介绍了在Objective-C中如何实现单例模式,通过使用synchronized关键字确保线程安全,以及提供了Singleton类的初始化、分配和获取共享实例的方法。
 1 #import "Singleton.h"
 2 
 3 
 4 @implementation Singleton
 5 static Singleton* instance;
 6 
 7 - (id)init
 8 {
 9     self = [super init];
10     if (self) {
11         // Initialization code here.
12     }
13     
14     return self;
15 }
16 
17 + (id)alloc
18 {
19     @synchronized([Singleton class])
20     {
21         instance = [super alloc];
22         return instance;
23     }
24     return nil;
25 }
26 
27 +(Singleton*)sharedInstance
28 {
29     @synchronized([Singleton class])
30     {
31         if(!instance)
32         {
33             [[self alloc] init];
34         }
35         
36         return instance;
37     }
38     return nil;
39 }
40 
41 - (void)sayHello
42 {
43     NSLog(@"Hello world!");
44 }
45 
46 @end

转载于:https://www.cnblogs.com/zhtf2014/archive/2011/03/11/1981554.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值