我有一个绑定到nsmutableablestring的文本字段。在按钮的操作项中,我想清除此字符串,但它抛出一个异常,说它是不可变的。
成员变量是
NSMutableString* firstName;
绑定到文本字段的属性在.h
中声明@property (copy) NSMutableString* firstName;
在按钮的操作中,以下行引发异常
[firstName setString:@""];
我在读取firstName中的值以访问文本字段中的内容时没有任何问题,因此绑定似乎正在起作用。
这是堆栈跟踪
Attempt to mutate immutable object with setString:
2012-01-22 14:48:58.084 testproj[2509:707] (
0 CoreFoundation 0x00007fff88233286 __exceptionPreprocess + 198
1 libobjc.A.dylib 0x00007fff857bdd5e objc_exception_throw + 43
2 CoreFoundation 0x00007fff882330ba +[NSException raise:format:arguments:] + 106
3 CoreFoundation 0x00007fff88233044 +[NSException raise:format:] + 116
4 CoreFoundation 0x00007fff882892dd mutateError + 93
5 testproj 0x00000001000035c4 -[AppController AddCustomer:] + 388
6 CoreFoundation 0x00007fff88222a1d -[NSObject performSelector:withObject:] + 61
7 AppKit 0x00007fff8f319710 -[NSApplication sendAction:to:from:] + 139
8 AppKit 0x00007fff8f319642 -[NSControl sendAction:to:] + 88
9 AppKit 0x00007fff8f31956d -[NSCell _sendActionFrom:] + 137
10 AppKit 0x00007fff8f318a30 -[NSCell trackMouse:inRect:ofView:untilMouseUp:] + 2014
11 AppKit 0x00007fff8f3988e0 -[NSButtonCell trackMouse:inRect:ofView:untilMouseUp:] + 489
12 AppKit 0x00007fff8f31763a -[NSControl mouseDown:] + 786
13 AppKit 0x00007fff8f2e20e0 -[NSWindow sendEvent:] + 6306
14 AppKit 0x00007fff8f27a68f -[NSApplication sendEvent:] + 5593
15 AppKit 0x00007fff8f210682 -[NSApplication run] + 555
16 AppKit 0x00007fff8f48f80c NSApplicationMain + 867
答案 0 :(得分:2)
您是否依赖于合成的二传手? copy
返回一个不可变的副本,因此您需要定义自己的setter。有关详细信息,请参阅http://vgable.com/blog/2009/03/17/mutable-property-and-copy-gotcha/