在开发中用单例存储项目中通用的全局变量是非常方便的,用法:

SingleSample.h中,

 

  1. #import <Foundation/Foundation.h> 
  2.  
  3. @interface SingleSample : NSObject 
  4.  
  5. @property (nonatomic, retain) NSString *user
  6.  
  7. + (SingleSample *)sharedSingleSample; 
  8.  
  9. @end

在SingleSample.m中,

 

  1. #import "SingleSample.h" 
  2.  
  3. @implementation SingleSample 
  4. @synthesize user
  5.  
  6. + (SingleSample *)sharedSingleSample 
  7.     static SingleSample *sharedSingleSample = nil; 
  8.     
  9.     @synchronized(self) 
  10.     { 
  11.         if (!sharedSingleSample) 
  12.             sharedSingleSample = [[SingleSample alloc] init]; 
  13.         return sharedSingleSample; 
  14.     } 
  15.  
  16. @end 

此为固定写法,在别的类中使用时,先引入头文件,然后直接调用[SingleSample sharedSingleSample].user,进行存储或取值。