0

I am trying to use a singleton to store variables that will be used across multiple view controllers. I need to be able to get the variables and also set them. How do I call a method in a singleton to change the variables stored in the singleton.

 total+=1079;
[var setTotal:total];

where var is a

static Singleton *var = nil;

I need to update the total and send to the setTotal method inside the singleton. But when I do this the setTotal method never gets accessed. The get methods work but the setTotal method does not. Please let me know what should. Below is some of my source code

   //
//  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
Johnny Cox
  • 1,873
  • 3
  • 17
  • 17

1 Answers1

1

You have attempted to implement your getters and setter as class methods instead of instance methods. Attributes are properties of your singleton, not of its class. For more on instance methods vs class methods in objective-c see here or here

You'll have better luck with something more like:

-(double) getTotal;
-(void) setTotal:(double) total;
-(double) getTax;
Community
  • 1
  • 1
joshOfAllTrades
  • 1,982
  • 14
  • 10