单例模式-ios

#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);

 

posted on 2014-08-16 18:33  clarenceV1  阅读(138)  评论(0编辑  收藏  举报

导航