//// UserContext.h// SingleDemo//// Created by andyyang on 9/30/13.// Copyright (c) 2013 andyyang. All rights reserved.//#import <Foundation/Foundation.h>@interface UserContext : NSObject@property (nonatomic,retain) NSString *username;@property(nonatomic,retain)NSString *email;+(id)sharedUserDefault;@end
//// UserContext.m// SingleDemo//// Created by andyyang on 9/30/13.// Copyright (c) 2013 andyyang. All rights reserved.//#import "UserContext.h"static UserContext *singleInstance=nil;@implementation UserContext+(id)sharedUserDefault{ if(singleInstance==nil) { @synchronized(self) { if(singleInstance==nil) { singleInstance=[[[self class] alloc] init]; } } } return singleInstance;}+ (id)allocWithZone:(NSZone *)zone;{ NSLog(@"HELLO");if(singleInstance==nil){ singleInstance=[super allocWithZone:zone];} return singleInstance;}-(id)copyWithZone:(NSZone *)zone{ NSLog(@"hello"); return singleInstance;}-(id)retain{ return singleInstance;}- (oneway void)release{}- (id)autorelease{ return singleInstance;}- (NSUInteger)retainCount{ return UINT_MAX;}@end
#import <Foundation/Foundation.h>#import "UserContext.h"int main(int argc, const char * argv[]){ @autoreleasepool { UserContext *userContext1=[UserContext sharedUserDefault]; UserContext *userContext2=[UserContext sharedUserDefault]; UserContext *userContext3=[[UserContext alloc] init]; UserContext *userContext4=[userContext1 copy]; // insert code here... NSLog(@"Hello, World!"); } return 0;}
result: