2013-09-24 64 views
0

我有一个完整的noob问题给你。我明显与obj-c生锈。我有一个简单的购物车类实现为单例,只是希望它存储单个NSMutableDictionary。我希望能够从应用程序中的任何位置将对象添加到此字典中。但对于一些(我敢肯定简单)的原因,它只是返回null。没有错误消息。Singleton NSMutableDictionary属性将不允许setObject:forKey

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 

而在我的VC我试图用设置:

- (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]); 
} 

谢谢

回答

3

你永远不会创建一个名为items的NSMutableDictionary对象。

您可以在ShoppingCart的init中创建它。

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

或sharedInstance

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

HAH!我需要离开计算机一天......呃。谢啦。 – crewshin

1

我也想补充它的更好(可以说)设置你的共享实例,像这样:

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

return instance; 
+0

你有复制和粘贴错误。 'sharedInstance.items'应该是'instance.items'。 – vikingosegundo

+0

谢谢。更新和修复。 –