我想使用一些单例类。我已创建它但不知道如何在我的viewControllers中使用它。
#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 :(得分:3)
您只需使用任何其他对象即可访问该属性。
[AppData sharedInstance].sharedString = @"foo";
或者
NSString *foo = [AppData sharedInstance].sharedString;