单例模式-ios

时间:2022-04-15 02:21:43
#import <Foundation/Foundation.h>

@interface UserContext : NSObject <NSCopying>

@property (nonatomic,copy) NSString *name;
@property (nonatomic,copy) NSString *emial; +(id) shareUsercontext; @end
#import "UserContext.h"

static UserContext *segtonInstance=nil;

@implementation UserContext

+(id) shareUsercontext{

    @synchronized(self){

    if(segtonInstance==nil){
segtonInstance=[[[self class] alloc] init];
} }
return segtonInstance;
} +(id) allocWithZone:(struct _NSZone *)zone{
if (segtonInstance==nil) {
segtonInstance=[super allocWithZone:zone];
}
return segtonInstance;
} - (id)copyWithZone:(NSZone *)zone{ return segtonInstance; } @end
/**单例模式***/
UserContext *usercontext=[UserContext shareUsercontext];
UserContext *usercontext2=[UserContext shareUsercontext];
UserContext *usercontext3=[[UserContext alloc] init];
UserContext *usercontext4=[usercontext copy];
NSLog(@"%p",usercontext);
NSLog(@"%p",usercontext2);
NSLog(@"%p",usercontext3);
NSLog(@"%p",usercontext4);