iOS OC C

单例

920 发布: 2015/11/10 08:34 本文总阅读量

实例0

.m

static YBRechargeType *chargeManeger = nil;

+(instancetype)chargeManeger {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        chargeManeger = [[super allocWithZone:NULL]init];
    });
    return chargeManeger;
}

+(instancetype)allocWithZone:(struct _NSZone *)zone {
    return [self chargeManeger];
}

实例1

UserContext.h头文件:

#import     

@interface UserContext : NSObject <NSCopying>

@property(nonatomic,copy)NSString *name;
@property(nonatomic,copy)NSString *email;        

//单例 类方法

+(id)shareUserContext;

@end
UserContext.m实现文件:       

#import "UserContext.h"

//单例对象

static UserContext *sigletonInstance=nil;

@implementation UserContext

//生成单例对象

+(id)shareUserContext{

     @synchronized(self){

      if (sigletonInstance==nil) {

                    sigletonInstance=[[[self class] alloc]init];

                }

            }

            return sigletonInstance;

        }

//下面的方法确保只有一个实例对象

+(id)allocWithZone: (NSZone *)zone{

      if (sigletonInstance==nil) {

                sigletonInstance=[super allocWithZone:zone];

            }

            return  sigletonInstance;

        }

-(id)copyWithZone: (NSZone *)zone

{

    return  sigletonInstance;

}

-(id)retain

{

    return  sigletonInstance;

}

-(oneway void)release

{

            

}

-(id)autorelease

{

    return  sigletonInstance;

}

-(NSUInteger)retainCount

{

   return UINT_MAX;

}

@end
main.m测试代码:

#import

#import "UserContext.h"

int main(int argc, const char * argv[]) {

     @autoreleasepool {

           UserContext *userContext1=[UserContext shareUserContext];

           UserContext *userContext2=[UserContext shareUserContext];

           UserContext *userContext3=[[UserContext alloc]init];

           UserContext *userContext4=[userContext3 copy];

                [userContext1 release];

                [userContext1 release];

                [userContext1 release];

                [userContext1 release];

                NSLog(@" ");

            }
         return 0;
     }