您的位置:首页 > 移动开发 > Objective-C

Objective-C ARC单例模式

2015-08-04 14:01 441 查看
//
//  MySingleton.h
//  SingleTon
//
//  Created by Realank on 15/8/4.
//  Copyright (c) 2015年 Realank. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface MySingleton : NSObject

@property (copy,nonatomic) NSString* string;

+(instancetype) sharedInstance;

// clue for improper use (produces compile time error)
+(instancetype) alloc __attribute__((unavailable("alloc not available, call sharedInstance instead")));
-(instancetype) init __attribute__((unavailable("init not available, call sharedInstance instead")));
+(instancetype) new __attribute__((unavailable("new not available, call sharedInstance instead")));

@end


//
//  MySingleton.m
//  SingleTon
//
//  Created by Realank on 15/8/4.
//  Copyright (c) 2015年 Realank. All rights reserved.
//

#import "MySingleton.h"

@implementation MySingleton

+(instancetype) sharedInstance {
static dispatch_once_t pred;
static id shared = nil; //设置成id类型的目的,是为了继承
dispatch_once(&pred, ^{
shared = [[super alloc] initUniqueInstance];
});
return shared;
}

-(instancetype) initUniqueInstance {

if (self = [super init]) {
_string = @"hello";
}

return self;
}

@end


//
//  main.m
//  SingleTon
//
//  Created by Realank on 15/8/4.
//  Copyright (c) 2015年 Realank. All rights reserved.
//

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

int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
MySingleton *sgt = [MySingleton sharedInstance];
NSLog(@"%@",sgt.string);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  objective-c 单例