2012-10-25 65 views

回答

9

您可以使用單例,也可以使用僅由類方法組成的類,並允許您訪問靜態數據。

這裏是ObjC一個基本的單執行:

@interface MySingleton : NSObject 
{ 
} 

+ (MySingleton *)sharedSingleton; 

@property(nonatomic) int prop; 
-(void)method; 

@end 

@implementation MySingleton 
@synthesize prop; 

+ (MySingleton *)sharedSingleton 
{ 
    static MySingleton *sharedSingleton; 

    @synchronized(self) 
    { 
    if (!sharedSingleton) 
     sharedSingleton = [[MySingleton alloc] init]; 

    return sharedSingleton; 
    } 
} 

-(void)method { 

} 

@end 

並且你使用這樣的:

int a = [MySingleton sharedSingleton].prop 

[[MySingleton sharedSingleton] method]; 

類方法基於類是:

@interface MyGlobalClass : NSObject 

+ (int)data; 

@end 

@implementation MySingleton 

static int data = 0; 
+ (int)data 
{ 
    return data; 
} 

+ (void)setData:(int)d 
{ 
    data = d; 
} 

@end 
+0

感謝。它運作良好。 – Raja