【发布时间】:2011-08-02 17:41:15
【问题描述】:
首先我读到了article
我认为我应该在我的程序中使用“复制”。 问题是使用 NSMutableDictionary 副本,它将终止。
***** 由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“-[__NSCFDictionary removeAllObjects]: mutating method sent to immutable object”**
我不知道“发送到不可变对象的变异方法”。 我没有将 NSDictionary 设置为 NSMutabledictionary 指针。
这是我的代码
.h 文件
@interface Button : NSObject {
@private
NSString* gID;
NSString* gBackColor;
NSString* gIconImage;
int gIndex;
BOOL gEnable;
BOOL gVisible;
NSString* gText;
NSMutableDictionary* gEvents;
BOOL gUseCircle;
}
@property (nonatomic,copy) NSString *ID;
@property (nonatomic,copy) NSString *BackColor;
@property (nonatomic,copy) NSString *IconImage;
@property int Index;
@property BOOL Enable;
@property BOOL Visible;
@property (nonatomic,copy) NSString *Text;
@property (nonatomic,getter=getEvents,retain) NSMutableDictionary *Events;
@property BOOL UseCircle;
@end
.m 文件
@implementation Button
@synthesize ID = gID;
@synthesize BackColor = gBackColor;
@synthesize IconImage = gIconImage;
@synthesize Index = gIndex;
@synthesize Enable = gEnable;
@synthesize Visible = gVisible;
@synthesize Text = gText;
@synthesize Events = gEvents;
@synthesize UseCircle = gUseCircle;
-(NSMutableDictionary*) getEvents
{
if (!gEvents)
{
gEvents = [[NSMutableDictionary alloc] initWithCapacity:20];
}
return gEvents;
}
- (id) init
{
self = [super init];
if (self != nil)
{
gID = @"";
gBackColor = @"";
gIconImage = @"";
gIndex = 0;
gText = @"";
gUseCircle = NO;
}
return self;
}
- (void) dealloc
{
[gID release];
[gBackColor release];
[gIconImage release];
[gText release];
[gEvents removeAllObjects];
[gEvents release];
gEvents = nil;
[super dealloc];
}
并实施
tBtnXML.Events = [self SplitEvents:tNode];
SplitEvents 函数:
-(NSMutableDictionary*) SplitEvents:(NSDictionary*)pEvents
{
NSMutableDictionary *tEvents = [[NSMutableDictionary alloc] initWithCapacity:5];
// code blabla
//.
//.
//.
[tEvents setObject:tEvent forKey:[NSNumber numberWithInt:tEventName]];
[tEvent release];
return [tEvents autorelease];
}
但我将 NSMutableDictionary* gEvents 属性从 copy 更改为 retain ,它执行正常。
谁能告诉我我的代码有什么问题?
如果我的代码与 dealloc 不正确,请告诉我。
谢谢你。
是的,所以我修复了我的二传手:
-(void) setEvents:(NSMutableDictionary*) pEvents
{
NSMutableDictionary* tNewDict = [pEvents mutableCopy];
[gEvents removeAllObjects];
[gEvents release];
gEvents = tNewDict;
}
这项工作没有错误。
这对我帮助很大。
但我不能投票>"
所以谢谢巴伐利亚 :)
【问题讨论】:
标签: objective-c copy properties nsmutabledictionary retain