我有一个以NSMutableDictionary
作为属性的类:
@interface Alibi : NSObject <NSCopying>
@property (nonatomic, copy) NSMutableDictionary * alibiDetails;
@end
使用以下构造函数:
- (Alibi *)init
{
self = [super init];
_alibiDetails = [NSMutableDictionary dictionary];
return self;
}
和复制方法:
- (Alibi *)copyWithZone:(NSZone *)zone
{
Alibi *theCopy = [[Alibi alloc] init];
theCopy.alibiDetails = [self.alibiDetails mutableCopy];
return theCopy;
}
当我尝试调用setObject:ForKey:
时,我收到运行时错误mutating method sent to immutable object
。
我在视图控制器中将Alibi
对象声明为@property (copy, nonatomic) Alibi * theAlibi;
,并使用self.theAlibi = [[Alibi alloc] init];
中的viewDidLoad
对其进行初始化。
崩溃的线是:
NSString * recipient;
recipient = @"Boss";
[self.theAlibi.alibiDetails setObject:recipient forKey:@"Recipient"];
请告诉我这里我做错了什么。我在iPhone上为iOS 5编码。
答案 0 :(得分:1)
你有一个'copy'属性,这意味着 - 你的NSMutableDictionary将调用-copy方法并在分配给合成的实例变量之前返回一个常规的NSDictionary。 This thread提供了一些有关解决此问题的选项的信息。
答案 1 :(得分:0)
为了完成这个主题,我将在下面包含我修订的Alibi
课程,这可以按照我的要求进行。如果有人注意到任何内存泄漏或其他问题,那将不胜感激。
@implementation Alibi
NSMutableDictionary *_details;
- (Alibi *)init
{
self = [super init];
_details = [NSMutableDictionary dictionary];
return self;
}
- (NSMutableDictionary *)copyDetails
{
return [_details mutableCopy];
}
- (NSMutableDictionary *)setDetails:(NSMutableDictionary *)value
{
_details = value;
return value;
}
- (void)addDetail:(id)value forKey:(id)key
{
[_details setObject:value forKey:key];
}
- (id)getDetailForKey:(id)key
{
return [_details objectForKey:key];
}
- (Alibi *)copyWithZone:(NSZone *)zone
{
Alibi *theCopy = [[Alibi alloc] init];
theCopy.serverId = [self.serverId copyWithZone:zone];
theCopy.user = [self.user copyWithZone:zone];
theCopy.startTime = [self.startTime copyWithZone:zone];
theCopy.endTime = [self.endTime copyWithZone:zone];
[theCopy setDetails:[self copyDetails]];
return theCopy;
}
@end