crewshin
crewshin

Reputation: 775

Singleton NSMutableDictionary property won't allow setObject:forKey

I have a complete noob question for you. I'm obviously rusty with obj-c. I have a simple shopping cart class implemented as a singleton and just want it to store a single NSMutableDictionary. I want to be able to add objects to this dictionary from anywhere in the app. But for some (I'm sure simple) reason it's just returning null. No error messages.

ShoppingCart.h:

#import <Foundation/Foundation.h>

@interface ShoppingCart : NSObject

// This is the only thing I'm storing here.
@property (nonatomic, strong) NSMutableDictionary *items;

+ (ShoppingCart *)sharedInstance;

@end

ShoppingCart.m:

// Typical singelton.
#import "ShoppingCart.h"

@implementation ShoppingCart

static ShoppingCart *sharedInstance = nil;

+ (ShoppingCart *)sharedInstance
{
    @synchronized(self)
    {
        if (sharedInstance == nil)
            sharedInstance = [[self alloc] init];
    }
    return(sharedInstance);
}

@end

And in my VC I'm trying to set it with:

- (IBAction)addToCartButton:(id)sender
{
    NSDictionary *thisItem = [[NSDictionary alloc] initWithObjects:@[@"test", @"100101", @"This is a test products description"] forKeys:@[@"name", @"sku", @"desc"]];

    // This is what's failing.
    [[ShoppingCart sharedInstance].items setObject:thisItem forKey:@"test"]; 

    // But this works.
    [ShoppingCart sharedInstance].items = (NSMutableDictionary *)thisItem; 

    // This logs null. Specifically "(null) has been added to the cart"
    DDLogCInfo(@"%@ has been added to the cart", [[ShoppingCart sharedInstance] items]); 
}

Thanks

Upvotes: 0

Views: 1109

Answers (2)

Ben Coffman
Ben Coffman

Reputation: 1740

I might also add it's better (arguably) to set up your shared instance like so:

static ShoppingCart *instance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
    instance = [[self alloc] init];
    instance.items = [NSMutableDictionary dictionary];
});

return instance;

Upvotes: 1

vikingosegundo
vikingosegundo

Reputation: 52227

You are never creating a NSMutableDictionary object named items.

You could create it in the init of ShoppingCart.

-(id)init 
{
    if(self = [super init]) {
        _items = [NSMutableDictionary dictionary];
    }
    return self;
}

or in sharedInstance

+ (ShoppingCart *)sharedInstance
{ 
    @synchronized(self)
    {
        if (sharedInstance == nil)
            sharedInstance = [[self alloc] init];
            sharedInstance.items = [NSMutableDictionary dictionary];
    }
    return(sharedInstance);
}

Upvotes: 3

Related Questions