Objective-C中嚴謹的單例模式


網上很多資料都只用一個dispatch_once其實是不嚴謹的

廢話不多說,直接上代碼(支持MRC/ARC混編)

 

頭文件:SingletonClass.h

//
//  SingletonClass.h
//  Singleton
//
//  Created by iospp on 15/12/25.
//  Copyright © 2015年 iospp. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface SingletonClass : NSObject

+ (instancetype)singletonInstance;

@end

實現文件:SingletonClass.m

//
//  SingletonClass.m
//  Singleton
//
//  Created by iospp on 15/12/25.
//  Copyright © 2015年 iospp. All rights reserved.
//

#import "SingletonClass.h"

@implementation SingletonClass

static SingletonClass *singletonInstance = nil;

#pragma mark - ARC

+ (instancetype)singletonInstance{

    static dispatch_once_t once;
    
    dispatch_once(&once, ^{
        singletonInstance = [[self alloc] init];
    });
    
    return singletonInstance;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone{

    static dispatch_once_t once;
    
    dispatch_once(&once, ^{
        singletonInstance = [super allocWithZone:zone];
    });
    
    return singletonInstance;
}

- (id)copyWithZone:(struct _NSZone *)zone{
    
    return singletonInstance;
}

#pragma mark - MRC

#if __has_feature(objc_arc)

#else

- (instancetype)retain{
    
    return singletonInstance;
}

- (NSUInteger)retainCount{
    
    return 1;//此處也可以返回max
}

- (oneway void)release{
    
}

- (instancetype)autorelease{
    
    return singletonInstance;
}

#endif

@end

 測試代碼:main.m

//
//  main.m
//  Singleton
//
//  Created by iospp on 15/12/25.
//  Copyright © 2015年 iospp. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "SingletonClass.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        
        SingletonClass *s1 = [SingletonClass singletonInstance];
        SingletonClass *s2 = [[SingletonClass alloc] init];
        SingletonClass *s3 = [s1 copy];
        
        NSLog(@"release前s1→%@",s1);
        NSLog(@"release前s2→%@",s2);
        NSLog(@"release前s3→%@",s3);
        
#if __has_feature(objc_arc)
        
#else
        
        [s1 release];
        [s2 release];
        [s3 release];
        
#endif
        
        NSLog(@"release后s1→%@",s1);
        NSLog(@"release后s2→%@",s2);
        NSLog(@"release后s3→%@",s3);
        
    }
    return 0;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM