你好,歡迎來到IOS教程網

 Ios教程網 >> IOS使用技巧 >> IOS技巧綜合 >> OC單例模式的實現

OC單例模式的實現

編輯:IOS技巧綜合
[摘要]本文是對OC單例模式的實現的講解,對學習IOS蘋果軟件開發有所幫助,與大家分享。

SingleClass.m

#import <Foundation/Foundation.h>
@class SingleClass;

static SingleClass *instance = nil;

@interface SingleClass : NSObject <NSCopying>
+ (instancetype)shareInstance;
@end

@implementation SingleClass
//類方法,獲取單例對象
+ (instancetype)shareInstance{
    if (!instance) {
        instance = [[self alloc] init];
    }
    return instance;
}
//類方法,調用對象的alloc方法時返回已存在的單例
+ (instancetype)allocWithZone:(struct _NSZone *)zone{
    if (!instance) {
        instance = [super allocWithZone:zone];
    }
    return instance;
}
//copy時,返回已存在的單例
- (id)copyWithZone:(NSZone *)zone{
    return instance;
}
//copy時,返回已存在的單例
- (id)copy{
    return instance;
}
@end

main.m

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        SingleClass *s1 = [SingleClass shareInstance];
        SingleClass *s2 = [SingleClass shareInstance];
        SingleClass *s3 = [[SingleClass alloc] init];
        SingleClass *s4 = [s1 copy];
        
        NSLog(@"%p",s1);
        NSLog(@"%p",s2);
        NSLog(@"%p",s3);
        NSLog(@"%p",s4);
    }
    return 0;
}

結果:

2015-03-22 22:24:21.201 SingleDemo[1349:61326] 0x1001066e0
2015-03-22 22:24:21.202 SingleDemo[1349:61326] 0x1001066e0
2015-03-22 22:24:21.202 SingleDemo[1349:61326] 0x1001066e0
2015-03-22 22:24:21.202 SingleDemo[1349:61326] 0x1001066e0
  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved