//
// Singleton.h
// 单例的标准写法
//
// Created by LZXuan on 14-8-24.
// Copyright (c) 2014年 LZXuan. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Singleton : NSObject
+ (Singleton *)sharedSingleton;
@end
//
// Singleton.m
// 单例的标准写法
//
// Created by LZXuan on 14-8-24.
// Copyright (c) 2014年 LZXuan. All rights reserved.
//
#import "Singleton.h"
@implementation Singleton
/*
开发中 一般写单例类 没有必要写标准单例 只需要写一个 非标准的函数+ sharedSingleton就够了,因为我们创建/获取单例 都是调用函数sharedSingleton
有些时候我项目要求 调用alloc 也要创建出单例 而且 可能会让单例调用 retain/copy、release autorelease 那么这个时候我们就必须要重写 官方的这些方法 保证 不管调用什么函数 始终程序只有一个对象
*/
//定义静态全局变量
static Singleton * single = nil;
+ (Singleton *)sharedSingleton{
//考虑线程安全
@synchronized(self){
if (single == nil) {
single = [[self alloc] init];
}
}
return single;
}
//调用 alloc的时候 会 调用allocWithZone函数
+ (id)allocWithZone:(NSZone *)zone
{
@synchronized(self) {
if (single == nil) {
//创建 对象
single = [super allocWithZone:zone];
return single;
}确保使用同一块内存地址
}
return single; //
}
- (id)copyWithZone:(NSZone *)zone
{
return self;//返回自己
}
- (id)retain
{
return self;//确保计数唯一
}
- (NSUInteger)retainCount
{
return UINT_MAX; //返回最大值
}
//oneway这一般是线程之间通信的接口定义。表示单向的调用
//使用oneway 异步调用 不使用那么是同步调用 可能会阻塞
- (oneway void)release
{
//do nothing
}
- (id)autorelease
{
return self;
}
/*
oneway is used with the distributed objects API, which allows use of objective-c objects between different threads or applications. It tells the system that it should not block the calling thread until the method returns. Without it, the caller will block, even though the method's return type is void. Obviously, it is never used with anything other than void, as doing so would mean the method returns something, but the caller doesn't get it.
*/
@end
方法二
//
// Singleton5.h
// 单例的标准写法
//
// Created by LZXuan on 14-8-24.
// Copyright (c) 2014年 LZXuan. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Singleton5 : NSObject
+ (id)sharedInstance;
@end
//
// Singleton5.m
// 单例的标准写法
//
// Created by LZXuan on 14-8-24.
// Copyright (c) 2014年 LZXuan. All rights reserved.
//
#import "Singleton5.h"
@implementation Singleton5
//ARC下或者 mrc gcd
//单例函数写法
+ (id)sharedInstance
{
static dispatch_once_t once = 0;//保证其block块在应⽤用中只执⾏行⼀一次
static id _sharedObject = nil;
dispatch_once(&once, ^{
_sharedObject = [[self alloc] init];
});
return _sharedObject;
}
//非arc
+ (Singleton5 *)sharedSingleton{
static Singleton5 *single = nil;
//考虑线程安全
@synchronized(self){
if (single == nil) {
single = [[self alloc] init];
}
}
return single;
}
@end