Just a Computer Graphics Studio & My Life

[iOS] 單例 (Singleton)

單例 (Singleton) 或稱單一實體,也就是程式運行時,此Class永遠只有一個實體。

Singleton.png

原本生成一個實體寫法:

HappyClass *class = [[HappyClass alloc] init];

程式每次執行到此,都會重新生成一個實體。若有多重執行緒,很有可能不小心生成多個實體;或是操作流程多變,也是可能會生成多個實體。

WiKi這麼解釋Singleton:

In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects. The term comes from the mathematical concept of a singleton.

圖解單例 (Singleton)

singleton2.png

那麼iOS要怎麼實現單例?

/**
 Theme: Singleton
 IDE: Xcode 9
 Language: Objective C
 Date: 106/11/22
 Author: HappyMan
 Blog: https://cg2010studio.com/
 */

@interface HappyClass : NSObject
+ (instancetype) sharedInstance;
@end

@implementation HappyClass

+ (instancetype) sharedInstance
{
    static HappyClass *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[HappyClass alloc] init];
    });
    return instance;
}
@end

使用方式像這樣即可:

HappyClass *class = [HappyClass sharedInstance];

AppDelegate.m也能如法炮製:

@implementation AppDelegate

+ (AppDelegate *)sharedAppDelegate

{

    return (id)[[UIApplication sharedApplication] delegate];

}

從此就能善用記憶體空間!

參考:再談 SingletonHow do I implement an Objective-C singleton that is compatible with ARC?Friday Q&A 2009-10-02: Care and Feeding of Singletons、WiKi – Singleton pattern

廣告

發表留言

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

您的留言將使用 WordPress.com 帳號。 登出 / 變更 )

Twitter picture

您的留言將使用 Twitter 帳號。 登出 / 變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 / 變更 )

Google+ photo

您的留言將使用 Google+ 帳號。 登出 / 變更 )

連結到 %s

標籤雲

%d 位部落客按了讚: