2012-08-28 32 views
0

我有具有NSMutableDictionary作爲屬性的類:的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編碼。

回答

1

你有一個'copy'屬性,意思就是說 - 你的NSMutableDictionary將得到-copy方法,並且在被分配到綜合實例變量之前返回一個常規的NSDictionary。 This thread提供了一些關於解決這個問題的選項。

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 
相關問題