我正在尝试使用单例来存储将在多个视图控制器中使用的变量。我需要能够获取变量并设置它们。如何在单例中调用方法来更改存储在单例中的变量。
total+=1079;
[var setTotal:total];
其中 var 是
static Singleton *var = nil;
我需要更新总数并发送到单例中的 setTotal 方法。但是当我这样做时, setTotal 方法永远不会被访问。get 方法有效,但 setTotal 方法无效。请让我知道应该怎么做。下面是我的一些源代码
//
// Singleton.m
// Rolo
//
// Created by on 6/28/12.
// Copyright (c) 2012 Johnny Cox. All rights reserved.
//
#import "Singleton.h"
@implementation Singleton
@synthesize total,tax,final;
#pragma mark Singleton Methods
+ (Singleton *)sharedManager
{
static Singleton *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[Singleton alloc] init];
// Do any other initialisation stuff here
});
return sharedInstance;
}
+(void) setTotal:(double) tot
{
Singleton *shared = [Singleton sharedManager];
shared.total = tot;
NSLog(@"hello");
}
+(double) getTotal
{
Singleton *shared = [Singleton sharedManager];
NSLog(@"%f",shared.total);
return shared.total;
}
+(double) getTax
{
Singleton *shared = [Singleton sharedManager];
NSLog(@"%f",shared.tax);
return shared.tax;
}
@end
//
// Singleton.h
// Rolo
//
// Created by on 6/28/12.
// Copyright (c) 2012 Johnny Cox. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Singleton : NSObject
@property (nonatomic, assign) double total;
@property (nonatomic, assign) double tax;
@property (nonatomic, assign) double final;
+ (id)sharedManager;
+(double) getTotal;
+(void) setTotal;
+(double) getTax;
@end