简体   繁体   English

Singleton NSMutableDictionary属性不允许setObject:forKey

[英]Singleton NSMutableDictionary property won't allow setObject:forKey

I have a complete noob question for you. 我有一个完整的菜鸟问题。 I'm obviously rusty with obj-c. 我显然对obj-c感到生锈。 I have a simple shopping cart class implemented as a singleton and just want it to store a single NSMutableDictionary. 我有一个实现为单例的简单购物车类,只希望它存储一个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. 但是出于某些原因(我敢肯定很简单),它只是返回null。 No error messages. 没有错误讯息。

ShoppingCart.h: 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: 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: 在我的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]); 
}

Thanks 谢谢

You are never creating a NSMutableDictionary object named items. 您永远不会创建名为items的NSMutableDictionary对象。

You could create it in the init of ShoppingCart. 您可以在ShoppingCart的初始化中创建它。

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

or in sharedInstance 或在sharedInstance中

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

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM