排序 NSMutableArray 内存泄漏
我的对象有一个私有 NSMutableArray 项目。我使用以下代码按大小顺序对项目中的对象进行排序:
-(void)sortItems{
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"size" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray = [items sortedArrayUsingDescriptors:sortDescriptors];
NSMutableArray* newArray = [[NSMutableArray alloc] initWithArray: sortedArray];
[self setItems:newArray];
[sortDescriptor release];
}
显然,这是内存泄漏,因为每次调用 sortItems 时,我都会分配新内存并分配项目以指向它。我尝试按如下方式释放旧内存:
NSMutableArray* newArray = [[NSMutableArray alloc] initWithArray: sortedArray];
NSMutableArray* oldArray = [self items];
[self setItems:newArray];
[oldArray release];
但这会产生 EXC_BAD_ACCESS 错误。我已经阅读了 objC 中的内存处理,并且我确信我在这里做了一些根本错误的事情。
任何帮助将不胜感激!
My object has a private NSMutableArray items. I am using the following code to sort the objects in items in size order:
-(void)sortItems{
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"size" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray = [items sortedArrayUsingDescriptors:sortDescriptors];
NSMutableArray* newArray = [[NSMutableArray alloc] initWithArray: sortedArray];
[self setItems:newArray];
[sortDescriptor release];
}
Obviously this is a memory leak here, because every time I call sortItems, I am allocing new memory and assigning items to point to it. I've tried releasing the old memory as follows:
NSMutableArray* newArray = [[NSMutableArray alloc] initWithArray: sortedArray];
NSMutableArray* oldArray = [self items];
[self setItems:newArray];
[oldArray release];
But that gives an EXC_BAD_ACCESS error. I've read up on memory handling in objC, and I'm convinced I'm doing something fundamentally wrong here.
Any help would be greatly appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在泄漏新数组,而不是旧数组:
基本规则是您必须释放已分配的任何内容,并且您通常不应该关心为任何人保留内容(即
[self setItems:]
),那些需要保留东西的人会自己做。我还建议将 self.items 制作为可变数组,并使用 [self.items sortUsingDescriptors:sortDescriptor 就地排序而不创建副本。
You're leaking the new array, not the old one:
The fundamental rule is that you must release anything that you have allocated, and you normally shouldn't care about keeping things retained for anyone (i.e.
[self setItems:]
), those who need something retained will do it themselves.I would also recommend making
self.items
a mutable array, and using[self.items sortUsingDescriptors:sortDescriptor
to sort inplace without creating a copy.在第一个示例中无法释放 newArray 是否有原因?
Is there a reason why you cannot release the newArray in your first example?