我有一个完整的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]);
}
谢谢
HAH!我需要离开计算机一天......呃。谢啦。 – crewshin