2016-12-30 61 views
0

我想使用一些單例類。我創建它,但不知道如何在我的viewControllers中使用它。objective-c如何使用singleton?

#import <Foundation/Foundation.h> 
#import <UIKit/UIKit.h> 

@interface AppData : NSObject 

//Singletone 
+(AppData*)sharedInstance; 
@property (strong,nonatomic) NSString *shardString; 

//Refs 

@end 

AppData.m:

#import "AppData.h" 

static AppData* staticInstance; 
@implementation AppData 

+(AppData*)sharedInstance 
    { 
if (staticInstance==nil) 
{ 

    staticInstance=[AppData new]; 

} 

return staticInstance; 
} 

@end 

現在我需要給QWERTY的NSString的值單的對象,如何從另一個viewControllers這個對象的訪問? ViewController.m:

#import "ViewController.h" 
#import "AppData.h" 

@interface ViewController() 

@end 

@implementation ViewController 

- (void)viewDidLoad { 
[super viewDidLoad]; 
// Do any additional setup after loading the view, typically from a nib. 

NSString *qwerty = @"i'm a singlton!"; 

[[AppData sharedInstance] ] 

NSLog(@"%@",); 

} 
+0

你基本上已經在那裏:'[AppData的sharedInstance] setShardString:QWERTY]'(或取決於是否這是一個錯字'setSharedString')。但有一件事是看看使用'dispatch_once'的單例創建示例。你現在可能不需要線程安全,但你會。 :) –

回答

3

您訪問屬性剛剛艾克你會爲任何其他對象。

[AppData sharedInstance].sharedString = @"foo"; 

或者

NSString *foo = [AppData sharedInstance].sharedString; 
+0

我想添加一個類型的NSInteger變量單身(@屬性(強,nonatomic)NSInteger * sharedInt;)但我得到:屬性與'保留(或強)'屬性必須是對象類型。怎麼修? –

+1

NSInteger是一種原始類型,而不是對象類型。它需要'@property(nonatomic,assign)NSInteger sharedInt;'。 – rmaddy

+1

僅供參考 - 請不要忘記接受解決您問題的答案。您只接受了針對您所有問題的單一答案。 – rmaddy