ios - 无法在单例中向 NSMutableDictionary 添加条目
<p><p>我有一个带有 NSMutableDictionary 的单例。我想从我的一个 View 中向该字典添加一个条目。由于我无法理解它不起作用并且我收到“NSDictionary setObject:forKey: unrecognized selector sent to instance”错误的原因。这似乎不应该那么难,但我找不到问题的答案。</p>
<p>所以我在 .xib 中连接了一个按钮来调用 createKey 方法和 kablooey。我还进行了测试以确保字典存在并且确实存在。</p>
<p>这是我的单例标题:</p>
<pre><code>#import <Foundation/Foundation.h>
@interface SharedAppData : NSObject <NSCoding>
{
NSMutableDictionary *apiKeyDictionary;
}
+ (SharedAppData *)sharedStore;
@property (nonatomic, copy) NSMutableDictionary *apiKeyDictionary;
-(BOOL)saveChanges;
@end
</code></pre>
<p>我的单例实现(重要部分)</p>
<pre><code> @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 = ;
NSString *testFile = ;
Boolean fileExists = [ fileExistsAtPath:testFile];
if(fileExists) {
sharedStore = ;
}
else{
sharedStore = [ init];
}
;
}
return sharedStore;
}
}
- (id)init {
if (self = ) {
apiKeyDictionary = [ init];
}
return self;
}
</code></pre>
<p>在我的 ViewController 标题中...</p>
<pre><code>#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
</code></pre>
<p>查看 Controller 实现:</p>
<pre><code>#import "AddKeyViewController.h"
#import "SharedAppData.h"
@interface AddKeyViewController ()
@end
@implementation AddKeyViewController
@synthesize apiName, apiKey, toolbar;
-(IBAction)createKey:(id)sender {
NSString *name = ;
NSString *key = ;
[[ apiKeyDictionary] setObject:key forKey:name];
}
@end
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>您的 <code>apiKeyDictionary</code> 属性设置为 <code>copy</code>。这会将 <code>copy</code> 消息发送到您在 <code>init</code> 方法中创建的 <code>NSMutableDictionary</code> 实例 - 返回的不是 <code>NSMutableDictionary</code> 而是<code>NSDictionary</code>。改为 <code>strong</code> 或 <code>retain</code>。</p></p>
<p style="font-size: 20px;">关于ios - 无法在单例中向 NSMutableDictionary 添加条目,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/12632891/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/12632891/
</a>
</p>
页:
[1]