singleton物件可被所有class所存取, 

類似全域變數的概念, 近日在專案上剛好接觸到它

所幸隨手既個筆記, 使用方法如下

Test1.h

#import <Foundation/Foundation.h>

@interface Test1 : NSObject

-(void)print1;
+(instancetype) object;

@end

Test1.m 

#import "Test1.h"

@implementation Test1

+(instancetype)object
{
    static Test1 *testObject = nil;
    if(testObject == nil)
    {
        testObject = [[Test1 alloc]init];
    }
    return testObject;
}

-(void)print1
{
    NSLog(@"hello ");
}


@end

 Test1.h導入(import)ViewController.m檔中, 若要調用此物件最後使用以下語法即可

-(void)prettyFunction
{
    [[Test1 object]print1];
}

 

arrow
arrow
    文章標籤
    singleton ios objectiveC
    全站熱搜

    Will 發表在 痞客邦 留言(0) 人氣()