当我收到异常:错误的NSMutableDictionary
- [__ NSCFDictionary的setObject:forKey:]:突变方法发送到不可变的对象”
有问题的行是:
[delegate.sharedData.dictFaves setObject:@"test" forKey:@"4"];
代表在MyViewController.m从而初始化:
delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
这是我的代表是如何在AppDelegate.h定义:
#import "CommonData.h"
...
@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
NSString *tempFave;
CommonData *sharedData;
}
@property (strong, nonatomic) NSString *tempFave;
@property (strong, nonatomic) CommonData *sharedData;
sharedData在AppDelegate.m这样初始化:
#import "AppDelegate.h"
...
@implementation AppDelegate
@synthesize sharedData;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
sharedData = [[CommonData alloc] init];
return YES;
}
sharedData在CommonData.h定义:
@interface CommonData : NSObject
{
NSMutableDictionary *dictAffirms;
NSMutableDictionary *dictFaves;
}
@property (nonatomic, copy) NSMutableDictionary *dictAffirms;
@property (nonatomic, copy) NSMutableDictionary *dictFaves;
共享数据执行文件CommonData.m:
#import "CommonData.h"
...
@implementation CommonData
@synthesize dictAffirms;
@synthesize dictFaves;
@end
我已经声明CommonData的成员是可变的。显然这是不够的。为了写入CommonData中的字典,还必须做些什么?
你在哪里分配init的NSMutableDictionaries。此外,这些都是艾瓦尔 - 你是否将这些属性公之于众? – bryanmac 2012-01-04 00:57:59
我编辑我的帖子,包括CommonData实现。你会看到没有构造函数。所以当'sharedData = alloc/init'这行时,我没有写出一个包含NSMutableDictionary alloc/init的构造函数。这是问题吗? – Bassman 2012-01-04 15:21:18
我们通常不会在objective-c中使用术语“构造函数”。它被称为初始化程序或-init方法。你不需要有一个初始化器。但是如果dictFaves将会有一个值,你必须从某处指定一个值。如果您指定了不可变字典,则会出现此问题。随意使用-mutableCopy方法将NSDictionary转换为NSMutableDictionary(记住在不使用ARC时分配给保留属性时自动释放副本)。 – 2012-01-05 20:25:16