0

我有一个具有 aNSMutableDictionary作为属性的类:

@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在视图控制器中声明了对象 as@property (copy, nonatomic) Alibi * theAlibi;并用self.theAlibi = [[Alibi alloc] init];in对其进行初始化viewDidLoad

崩溃的行是:

NSString * recipient;
recipient = @"Boss";
[self.theAlibi.alibiDetails setObject:recipient forKey:@"Recipient"];

请让我知道我在这里做错了什么。我正在为 iPhone 上的 iOS 5 编写代码。

4

2 回答 2

1

您有一个“复制”属性,这意味着 - 您的 NSMutableDictionary 将调用 -copy 方法并在分配给合成实例变量之前返回一个常规 NSDictionary 。该线程提供了有关解决此问题的一些选项的一些信息。

于 2012-08-28T09:22:02.553 回答
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
于 2012-08-28T10:02:07.723 回答