【发布时间】:2011-06-20 16:53:59
【问题描述】:
这里是新人(这个论坛和一般的 Xcode),所以请多多包涵。
在过去的几天里,我花了几个小时断断续续地试图找出我到底做错了什么,但我似乎无法查明我的问题。
这是我的代码的相关部分(我相信)。
在标题中:
@interface BlahViewController : UIViewController {
NSMutableString *display;
}
@property (nonatomic, retain) NSMutableString *display;
主要是:
@implementation BlahViewController
@synthesize display;
- (void)viewDidLoad {
self.display = [[NSMutableString alloc] init];
}
- (void)anotherFunction:(UIButton *)sender {
NSString *info = [[sender titleLabel] text];
[self.display appendString:info];
}
我运行代码,按下 UIButton,我得到一个错误。这是最初的抛出:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM appendString:]: unrecognized selector sent to instance 0x4e3d300' ***
谢谢!
编辑:请求了整个堆栈跟踪,所以在这里(在查看堆栈后,我意识到可能存在混淆,我目前正在编写一个非常基本的计算器,因此 ViewController 等应考虑该背景和“ anotherFunction" = "digitPressed" 在这种特殊情况下):
* 首次抛出时调用堆栈: (
0 CoreFoundation 0x00e345a9 异常预处理 + 185
1 libobjc.A.dylib 0x00f88313 objc_exception_throw + 44
2 CoreFoundation 0x00e360bb -[NSObject(NSObject) 不识别选择器:] + 187
3 CoreFoundation 0x00da5966 __转发 + 966
4 核心基础 0x00da5522 _CF_forwarding_prep_0 + 50
5 计算器 0x0000273b -[CalculatorViewController digitPressed:] + 113
6 UIKit 0x002bb4fd -[UIApplication sendAction:to:from:forEvent:] + 119
7 UIKit 0x0034b799 -[UIControl sendAction:to:forEvent:] + 67
8 UIKit 0x0034dc2b -[UIControl(内部)_sendActionsForEvents:withEvent:] + 527
9 UIKit 0x0034c7d8 -[UIControl touchesEnded:withEvent:] + 458
10 UIKit 0x002dfded-[UIWindow _sendTouchesForEvent:] + 567
11 UIKit 0x002c0c37 -[UIApplication sendEvent:] + 447
12 UIKit 0x002c5f2e _UIApplicationHandleEvent + 7576
13 图形服务 0x01723992 PurpleEventCallback + 1550
14 核心基础 0x00e15944 CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION + 52
15 核心基础 0x00d75cf7 __CFRunLoopDoSource1 + 215
16 核心基础 0x00d72f83 __CFRunLoopRun + 979
17 核心基础 0x00d72840 CFRunLoopRunSpecific + 208
18 核心基础 0x00d72761 CFRunLoopRunInMode + 97
19 图形服务 0x017221c4 GSEventRunModal + 217
20 图形服务 0x01722289 GSEventRun + 115
21 UIKit 0x002c9c93 UIApplicationMain + 1160
22 计算器 0x00002254 主 + 102
23 计算器 0x000021e5 开始 + 53
)
在抛出“NSException”实例后调用终止
当前语言:自动;目前objective-c
【问题讨论】:
-
'self.display = [[NSMutableString alloc] init];'线是内存泄漏。您应该改用
self.display = [[[NSMutableString alloc] init] autorelease];或self.display = [NSMutableString string]; -
如果我在 viewDidUnload 方法中释放它是不是内存泄漏?因为现在的安排方式是 -viewDidLoad alloc/inits 和 -viewDidUnload 释放。
-
'display' 是一个具有 retain 内存管理的属性。因此,当您执行
self.display = [[NSMutableString alloc] init];时,它严格等同于[display release]; display = [[[NSMutableString alloc] init] retain];,并且保留计数为2。如果您在 viewDidUnload 方法中有self.display = nil,则将保留计数减一,因此仍有一些为字符串分配的内存,但无法再访问它。这是泄漏。