0

我有一个完整的菜鸟问题要问你。我显然对 obj-c 生疏了。我有一个简单的购物车类实现为单例,只希望它存储一个 NSMutableDictionary。我希望能够从应用程序的任何位置将对象添加到此字典中。但是出于某些(我确定很简单)的原因,它只是返回空值。没有错误信息。

购物车.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

购物车.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]); 
}

谢谢

4

2 回答 2

3

您永远不会创建名为 items 的 NSMutableDictionary 对象。

您可以在 ShoppingCart 的初始化中创建它。

-(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);
}
于 2013-09-24T00:19:10.617 回答
1

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;
于 2013-09-24T00:44:11.307 回答