我有一个完整的菜鸟问题要问你。我显然对 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]);
}
谢谢