在这种情况下我如何泄漏 NSString ?
我有一个表视图,最后一行有一个字符串。
@interface MyTableViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
{
NSString *loadingMessage;
}
@property (retain) NSString *loadingMessage;
@synthesize loadingMessage;
- (UITableViewCell *)tableView:(UITableView *)pTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//some stuff...
cell.textLabel.text = loadingMessage;
}
然后,当发生某些事件时,我将更改加载消息:
-(void)requestFailed:(NSError*)error {
self.loadingMessage = [NSString stringWithFormat:@"Failed with error: %@", error];
}
根据仪器,我在这里泄漏了loadingMessage字符串......但我不明白为什么。我认为 stringWithFormat 的计数是 +0,而 setter 是 +1。当我解除分配时,我也会释放该字符串。我做错了什么?
I have a tableview that has a string on the last row.
@interface MyTableViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
{
NSString *loadingMessage;
}
@property (retain) NSString *loadingMessage;
@synthesize loadingMessage;
- (UITableViewCell *)tableView:(UITableView *)pTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//some stuff...
cell.textLabel.text = loadingMessage;
}
Then when some event happens, I will be changing the loading message:
-(void)requestFailed:(NSError*)error {
self.loadingMessage = [NSString stringWithFormat:@"Failed with error: %@", error];
}
According to instruments I am leaking the loadingMessage string in here... But I don't see why. I thought the count for stringWithFormat is +0, and the setter is +1. I release the string when I dealloc as well. What am i doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您发布的代码是正确的。事实上,
stringWithFormat
返回一个自动释放的对象,因此您可以将其直接分配给保留的属性。因此,要么您正在代码中进行其他分配,或者更可能的是,您没有在
dealloc
中释放loadingMessage
。只是一个假设。
The code you posted is correct. Indeed,
stringWithFormat
returns an autoreleased object, so you can assign it directly to a retained property.So, either you are doing some other assignment in your code, or, more probably, you are not releasing
loadingMessage
in yourdealloc
.Just an hypothesis.
Sergio 是对的,代码没有任何问题,但我发现字符串属性需要复制而不是保留。
尝试
@property (copy,readwrite) NSString *loadingMessage;
可能会阻止泄漏
Sergio is right , theres nothing wrong with the code but I have found that string properties need to be copy rather than retain.
Try
@property (copy,readwrite) NSString *loadingMessage;
Might stop the leak