2016-12-30 58 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