完全な初歩的な質問があります。私は明らかに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]);
}
ありがとう