2

我有一个带有 NSMutableDictionary 的单例。我想从我的一个视图中向该字典添加一个条目。由于我无法理解它不起作用并且我收到“NSDictionary setObject:forKey: unrecognized selector sent to instance”错误的原因。这似乎不应该那么难,但我找不到问题的答案。

所以我在我的.xib 中连接了一个按钮来调用createKey 方法和kablooey。我还进行了测试以确保字典存在并且确实存在。

这是我的单例标题:

#import <Foundation/Foundation.h>

@interface SharedAppData : NSObject <NSCoding>
{
    NSMutableDictionary *apiKeyDictionary;
}

+ (SharedAppData *)sharedStore;

@property (nonatomic, copy) NSMutableDictionary *apiKeyDictionary;

-(BOOL)saveChanges;

@end

我的单例实现(重要部分)

 @interface SharedAppData()
    @end

    @implementation SharedAppData

    @synthesize apiKeyDictionary;

    static SharedAppData *sharedStore = nil;

+(SharedAppData*)sharedStore {

        @synchronized(self){
        if(sharedStore == nil){
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *documentsDirectory = [paths objectAtIndex:0];
            NSString *testFile = [documentsDirectory stringByAppendingPathComponent:@"testfile.sav"];
            Boolean fileExists = [[NSFileManager defaultManager] fileExistsAtPath:testFile];

            if(fileExists) {
                sharedStore = [NSKeyedUnarchiver unarchiveObjectWithFile:testFile];
            }
            else{
                sharedStore = [[super allocWithZone:NULL] init];
            }

            [sharedStore setSaveFile:testFile];
        }

            return sharedStore;
        }
}

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

在我的视图控制器标题中......

#import <UIKit/UIKit.h>
#import "SharedAppData.h"

@interface AddKeyViewController : UIViewController <UITextFieldDelegate>
{
    UIButton *addKey;
}

@property (weak, nonatomic) IBOutlet UITextField *apiName;
@property (weak, nonatomic) IBOutlet UITextField *apiKey;

-(IBAction)createKey:(id)sender;

@end

查看控制器实现:

#import "AddKeyViewController.h"
#import "SharedAppData.h"

@interface AddKeyViewController ()

@end

@implementation AddKeyViewController

@synthesize apiName, apiKey, toolbar;

-(IBAction)createKey:(id)sender {

    NSString *name = [apiName text];
    NSString *key = [apiKey text];

    [[[SharedAppData sharedStore] apiKeyDictionary] setObject:key forKey:name];
}

@end
4

2 回答 2

2

我怀疑问题在于您的财产是“复制”而不是“强”;当你设置它时,mutanle 字典被复制到一个不可变的字典中。尝试将您的属性更改为“强”。

于 2012-09-28T02:45:55.000 回答
2

您的apiKeyDictionary属性设置为copy。这会将copy消息发送到NSMutableDictionary您在init方法中创建的实例 - 返回不是一个,NSMutableDictionary而是一个NSDictionary. 将其更改为strongor retain

于 2012-09-28T02:46:13.777 回答