排序数组时内存泄漏

时间:2012-02-09 22:23:08

标签: 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){

我怎么能解决这个漏洞?

2 个答案:

答案 0 :(得分:2)

完全删除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;

答案 1 :(得分:0)

您正在返回保留的对象:arr。返回保留目标的方法Objective-C命名规则只从new开始,或包含单词copy

无需分配/初始化arrsortedArrayUsingComparator方法将返回自动释放的NSArray

不要使用前缀“get”命名方法,除非它们通过引用参数返回结果。这是基本的Objective-C命名规则,ARC依赖于遵守的命名规则。

请参阅Apple的文档Introduction to Coding Guidelines for Cocoa