我试图使用单例概念来保留GPS信息,但我不知道问题出在哪里,我的变量只显示为零。
Singleton.h:
@interface Singleton : NSObject
@property (readwrite) NSString *propertyA;
@property (readwrite) NSString *propertyB;
@property (readwrite) NSString *propertyC;
+ (Singleton *)sharedInstance;
@end
Singleton.m:
#import "Singleton.h"
@interface Singleton ()
{
NSString *variableA;
NSString *variableB;
NSString *variableC;
}
@end
@implementation Singleton
static Singleton *sharedInstance = nil;
+ (Singleton *)sharedInstance
{
@synchronized(self) {
if (sharedInstance == nil) {
sharedInstance = [[Singleton alloc] init];
}
}
return sharedInstance;
}
+ (id)allocWithZone:(NSZone *)zone {
@synchronized(self) {
if (sharedInstance == nil) {
sharedInstance = [super allocWithZone:zone];
return sharedInstance;
}
}
return nil;
}
- (id)init
{
self = [super init];
if (self)
{
variableA = nil;
variableB = nil;
variableC = nil;
}
return self;
}
@end
OverlayViewController.m中的:
#import "Singleton.h"
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(@"didUpdateToLocation: %@", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
_longitudeLabel.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude];
_latitudeLabel.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];
}
// Setting properties
NSString *variableA = _latitudeLabel.text;
[[Singleton sharedInstance] setPropertyA:variableA];
}
然后我再回想一下这个价值......
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *variableA = [[Singleton sharedInstance] propertyA];
NSLog(@"Latitude = %.8f", variableA);
}
感谢瑞吉斯
答案 0 :(得分:0)
我的第一个猜测是你在任何地方都没有@synthesize,所以没有setter / getters
如果这不起作用,那么你应该将你的变量声明移动到你的.h文件中,我不明白为什么你会在你的.m上使用它们
我指的是:
@interface Singleton ()
{
NSString *variableA;
NSString *variableB;
NSString *variableC;
}
@end
修改强> 处理单身人士时的两个好习惯:
1)在您的方法中声明您的static ClassName *singleton
,以便您班级中的其他方法无法直接访问它,并且需要使用[[self class] sharedInstance];
2)使用dispatch_once进行线程安全
+ (FooBar *)sharedInstance {
static dispatch_once_t pred;
static FooBar *_sharedInstance = nil;
dispatch_once(&pred, ^{
_sharedInstance = [[[self class] alloc] init];
});
return _sharedInstance;
}
答案 1 :(得分:0)
@property (readwrite) NSString *propertyA;
@property (readwrite) NSString *propertyB;
@property (readwrite) NSString *propertyC;
我猜上面的变量没有setter和getter,意味着你需要@synthesize它们。
这就是为什么下面的代码没有设置PropertyA值。
[[Singleton sharedInstance] setPropertyA:variableA];