我有一个完整的菜鸟问题。 obj-c我显然很生气。我有一个简单的购物车类实现为单身,只是希望它存储一个NSMutableDictionary。我希望能够从应用程序的任何位置向此字典添加对象。但对于一些人(我很确定很简单)的原因,它只是返回null。没有错误消息。
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]);
}
由于
答案 0 :(得分: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);
}
答案 1 :(得分:1)
我可能还会更好地(可以说)设置您的共享实例,如下所示:
static ShoppingCart *instance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[self alloc] init];
instance.items = [NSMutableDictionary dictionary];
});
return instance;