objective-c - 数组排序时内存泄漏

标签 objective-c

我有以下功能

- (NSArray *) getUsers : (days) aDay {

    NSArray *arr = [[[NSArray alloc] init] autorelease];

    for (User *e in [week objectAtIndex:aDay]) {
        //Get distance to user
        e.place.distance = [[LocationManager sharedLocationManager] getDistanceWithLat:e.place.latitude Lon:e.place.longitude];
    }

    //Sort the array
    arr = [ [week objectAtIndex:aDay] sortedArrayUsingComparator:^(id obj1, id obj2){
            User *e1 = (User *)obj1;
            User *e2 = (User *)obj2;

            if (e1.place.distance <= e2.place.distance) {
                return (NSComparisonResult)NSOrderedAscending;
            } else {
                return (NSComparisonResult)NSOrderedDescending;
            }
        return (NSComparisonResult)NSOrderedSame;
    }];

    [arr retain];

    return arr;
}

它泄漏了,我不知道如何修复它。如果我删除 [arr retian] 那么应用程序崩溃。

当我执行操作配置文件时,仪器在此行显示 100% 泄漏:

   arr = [ [week objectAtIndex:aDay] sortedArrayUsingComparator:^(id obj1, id obj2){

如何修复此泄漏?

最佳答案

删除NSArray *arr = [[[NSArray alloc] init] autorelease];[arr retain];根本不。在第一行中,您分配了内存,但是在排序时引用了新数组并发生了泄漏。

NSArray *arr = [ [week objectAtIndex:aDay] sortedArrayUsingComparator:^(id obj1, id obj2){
            User *e1 = (User *)obj1;
            User *e2 = (User *)obj2;

            if (e1.place.distance <= e2.place.distance) {
                return (NSComparisonResult)NSOrderedAscending;
            } else {
                return (NSComparisonResult)NSOrderedDescending;
            }
        return (NSComparisonResult)NSOrderedSame;
    }];

return arr;

关于objective-c - 数组排序时内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9219764/

相关文章:

objective-c - 保留 iOS 标签栏更多页面

iphone - 检查 NSString 崩溃的子字符串

objective-c - 如何禁用clang中的-Wcompare-distinct-pointer-types警告?

objective-c - 将 NSSlider 与 NSTableView 绑定(bind)

iphone - ARC - UIWebView/UIViewController 留在内存中吗?

iphone - 增加框架时自动调整 mask 大小问题 - iOS

iphone - UITableView 重复背景与 2 个图像

objective-c - 将 .NET 中的 DateTime 对象格式化为 objective-c 的 NSDate

objective-c - 核心数据 : update in background and reading in main thread causes dead lock

objective-c - 具有多个目标的 Swift 生成的 header