//
// UserContext.h
// 单例
//
// Created by on 14-11-10.
// Copyright (c) 2014年 Apple. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface UserContext : NSObject
@property(nonatomic, copy) NSString *username;
@property(nonatomic, copy) NSString *email;
// 约定俗成,单例一般命名为shareXXX或者defaultXXX
+ (id) shareUserContext;
@end
//
// UserContext.m
// 单例
//
// Created by on 14-11-10.
// Copyright (c) 2014年 Apple. All rights reserved.
//
#import "UserContext.h"
//static UserContext *segtonInstance = nil;
__strong static UserContext *singleton = nil;
@implementation UserContext
/************ 非ARC单例模式 *************/
//+ (id) shareUserContext {
// @synchronized(self) {
// if (segtonInstance == nil) {
// segtonInstance = [[[self class] alloc] init];
// }
// }
// return segtonInstance;
//}
//
//+ (id) allocWithZone:(struct _NSZone *)zone {
// @synchronized(self) {
// if (segtonInstance == nil) {
// segtonInstance = [super allocWithZone:zone];
// return segtonInstance;
// }
// }
// return nil;
//}
/************ ARC单例模式 *************/
+ (id) shareUserContext {
// dispatch_once不仅意味着代码仅会被运行一次,而且还是线程安全的
static dispatch_once_t pred = 0;
dispatch_once(&pred, ^{
singleton = [[super allocWithZone:NULL] init];
});
return singleton;
}
+ (id)allocWithZone:(NSZone *)zone
{
return [self shareUserContext];
}
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
@end
//
// main.m
// 单例
//
// Created by on 14-11-10.
// Copyright (c) 2014年 Apple. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "UserContext.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
UserContext *user = [[UserContext alloc] init];
UserContext *user2 = [UserContext shareUserContext];
NSLog(@"%d", user == user2);
}
return 0;
}