0

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

ありがとう

4

2 に答える 2

3

items という名前の NSMutableDictionary オブジェクトを作成することはありません。

ShoppingCart の init で作成できます。

-(id)init 
{
    if(self = [super init]) {
        _items = [NSMutableDictionary dictionary];
    }
    return self;
}

または共有インスタンスで

+ (ShoppingCart *)sharedInstance
{ 
    @synchronized(self)
    {
        if (sharedInstance == nil)
            sharedInstance = [[self alloc] init];
            sharedInstance.items = [NSMutableDictionary dictionary];
    }
    return(sharedInstance);
}
于 2013-09-24T00:19:10.617 に答える
1

また、次のように共有インスタンスを設定する方が (ほぼ間違いなく) 優れていると付け加えるかもしれません。

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 に答える