ios開發答疑錄系列​–關於IOS單利的思考

來源:互聯網
上載者:User
============================================================博文原創,轉載請聲明出處電子咖啡(原id藍岩)============================================================

近日我寫了一段單利代碼,如下,有些思考

#import "WQPlaySound.h"#define DISPOSE_INTERVAL 3@implementation WQPlaySoundstatic WQPlaySound* instance=nil;static NSString* lock=@"";+(WQPlaySound*)shareWQPlaySound{        //同步防止多線程訪問,這裡本來想用instance來作為鎖對象的,但是當instance為nil的時候不能作為鎖對象    @synchronized(lock){        if (!instance) {            instance= [[WQPlaySound alloc]init];        }    }        return instance;}

問題一:單利需要release嗎?

No class should need to retain a pointer to a singleton class. Singleton class itself keeps a pointer to its instance. Basically, when the user wants to use a singleton, they will request it through a class method (by convention often starting with shared). This method will check if the singleton has been initialized. If not, it will perform the initialization. If there is already an existing instance in memory, it will just return it. Usually, a singleton object will live in memory for the life of the application.

單利生命週期和appdelegate是一樣的,因此不需要release


問題二:@synchronized(lock){...}的lock同步鎖對象如果是空的話,還工作嗎?

Nil value used as mutex for @synchronized() (no synchronization will occur)

這是xcode提示我的,因此不可以用nil,我們可以用Null 字元串@“”來加鎖

修改----2012-11-06

剛才@DolphinOrca 對My Code提出了疑問,我測試了一下,卻是是我的理解錯誤,在此表示對DolphinOrca 的感謝。

DolphinOrca提出把@synchronized(lock) 替換成@synchronized(self)可以更方便的進行同步。而我當時認為這樣子不可以,因為在@synchronized(self) 的時候,self還沒有被init,所以self是nil,synchronized(nil)無效。

後來我又做了實驗,證明我的觀點是錯誤的。

首先建立單利Singleton

@implementation Singletonstatic Singleton* instance=nil;static int i=0;+(Singleton*)share{    NSLog(@"self:%@----i++:%d",self,i++);        @synchronized(instance){//注意這次是instance不是self        if (instance==nil) {                        if((i)>1){ //i>1是為了前兩個線程在這裡停留兩秒,讓第三個線程先alloc然後自己再alloc                [NSThread sleepForTimeInterval:2];            }            instance = [[Singleton alloc] init];        }    }    return instance;}

然後在另一個檔案中啟動三個線程去獲得這個單利,然後列印看三個單利是否相同。

- (void)viewDidLoad{    [super viewDidLoad];    //啟動三個線程去調用單利    [NSThread detachNewThreadSelector:@selector(getSingleton) toTarget:self withObject:nil];    [NSThread detachNewThreadSelector:@selector(getSingleton) toTarget:self withObject:nil];    [NSThread detachNewThreadSelector:@selector(getSingleton) toTarget:self withObject:nil];}-(void)getSingleton{    Singleton* s= [Singleton share];    NSLog(@"signle:%@",s);}

結果如下

2012-11-06 17:21:46.933 SingletonDemo[811:3c07] self:Singleton----i++:02012-11-06 17:21:46.934 SingletonDemo[811:4303] self:Singleton----i++:12012-11-06 17:21:46.934 SingletonDemo[811:4603] self:Singleton----i++:22012-11-06 17:21:48.948 SingletonDemo[811:4603] signle:<Singleton: 0x744a5e0> //<<<<--------2012-11-06 17:21:48.948 SingletonDemo[811:4303] signle:<Singleton: 0x91174a0>2012-11-06 17:21:48.948 SingletonDemo[811:3c07] signle:<Singleton: 0x714b6e0>

可以看到輸出的singleton對象為三個不同的對象,這是我原來的思想。

線面我門將synchronized鎖換成self,其他不變,重新運行,

 @synchronized(self)

輸出結果為:

2012-11-06 17:41:32.863 SingletonDemo[866:4603] self:Singleton----i++:1  //self為Singleton類2012-11-06 17:41:32.863 SingletonDemo[866:3c07] self:Singleton----i++:02012-11-06 17:41:32.863 SingletonDemo[866:4103] self:Singleton----i++:22012-11-06 17:41:34.879 SingletonDemo[866:4603] signle:<Singleton: 0x750e120>2012-11-06 17:41:34.879 SingletonDemo[866:3c07] signle:<Singleton: 0x750e120>2012-11-06 17:41:34.879 SingletonDemo[866:4103] signle:<Singleton: 0x750e120>

可以看到獲得的單利為同一對象。

後來思考,這裡self是以類class為鎖,所以不存在nil的問題。

關於線程同步的問題,我會在以後的blog中繼續研究

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.