我有一个带有 NSMutableDictionary 的单例。我想从我的一个 View 中向该字典添加一个条目。由于我无法理解它不起作用并且我收到“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;
}
在我的 View Controller 标题中...
#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)createKeyid)sender;
@end
查看 Controller 实现:
#import "AddKeyViewController.h"
#import "SharedAppData.h"
@interface AddKeyViewController ()
@end
@implementation AddKeyViewController
@synthesize apiName, apiKey, toolbar;
-(IBAction)createKeyid)sender {
NSString *name = [apiName text];
NSString *key = [apiKey text];
[[[SharedAppData sharedStore] apiKeyDictionary] setObject:key forKey:name];
}
@end
您的 apiKeyDictionary
属性设置为 copy
。这会将 copy
消息发送到您在 init
方法中创建的 NSMutableDictionary
实例 - 返回的不是 NSMutableDictionary
而是NSDictionary
。改为 strong
或 retain
。
关于ios - 无法在单例中向 NSMutableDictionary 添加条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12632891/
欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) | Powered by Discuz! X3.4 |