iphone中单例的使用

MySharedClass.h

@interface MySharedClass : NSObject {

      NSString *sharedString;
}
@property (nonatomic,retain) NSString *sharedString;

+ (MySharedClass *)newInstance;

@end

MySharedClass.m
@implementation MySharedClass
@synthesize sharedString;
static MySharedClass *sharedInstance = nil; 
+ (MySharedClass *)newInstance{
  @synchronized(self){
    if(sharedInstance == nil)
    {
       sharedInstance = [[MySharedClass alloc] init];
    }
}
   return sharedInstance;
}
@end
需要时  
- (void)viewDidLoad
{
    shareClass = [MySharedClass newInstance];
    [super viewDidLoad];
}
用就可以了

你可能感兴趣的:(iphone中单例的使用)