转载自:http://huqiji.iteye.com/blog/2037991
参考apple官方例子单例模式(singleton)
- //
- // DBHelper.h
- // KeepSafe
- //
- // Created by RockeyCai on 14-3-28.
- // Copyright (c) 2014年 rockycai. All rights reserved.
- //
- #import <Foundation/Foundation.h>
- @interface DBHelper : NSObject
- //获取单例对象
- +(DBHelper *)getDBHelperSingleton;
- @end
- //
- // DBHelper.m
- // KeepSafe
- //
- // Created by RockeyCai on 14-3-28.
- // Copyright (c) 2014年 rockycai. All rights reserved.
- //
- #import "DBHelper.h"
- static DBHelper *dbHelper = nil;
- @implementation DBHelper
- +(DBHelper *)getDBHelperSingleton{
- @synchronized(self){ //为了确保多线程情况下,仍然确保实体的唯一性
- if (!dbHelper) {
- [[self alloc] init]; //该方法会调用 allocWithZone
- }
- }
- return dbHelper;
- }
- +(id)allocWithZone:(NSZone *)zone{
- @synchronized(self){
- if (!dbHelper) {
- dbHelper = [super allocWithZone:zone]; //确保使用同一块内存地址
- return dbHelper;
- }
- }
- return nil;
- }
- - (id)copyWithZone:(NSZone *)zone;{
- return self; //确保copy对象也是唯一
- }
- -(id)retain{
- return self; //确保计数唯一
- }
- - (unsigned)retainCount
- {
- return UINT_MAX; //装逼用的,这样打印出来的计数永远为-1
- }
- - (id)autorelease
- {
- return self;//确保计数唯一
- }
- - (oneway void)release
- {
- //重写计数释放方法
- }
- @end