Question

To return a NSArray or NSDictionary, I have seen most people use the below implementation and this is also what some books suggest. (iOS Development A Practical Approach - )

OPTION 1

  -(NSArray*)listOfStudents{

    NSMutableArray *temp = [[NSMUtableArray alloc] init];

    //Add elements to the array
    //
    //
    //
    NSArray *students =  [NSArray arrayWithArray:temp];

    return students;
    }



 -(void)viewWillAppear{

    self.studentsList = [self listOfStudents];
    }

But can this same be done by the below way also?

OPTION 2

 -(NSArray*)newListOfStudents{

    NSMutableArray *temp = [[NSMUtableArray alloc] init];
    NSArray *students = [[NSArray alloc]initWithArray:temp];
    [temp release];
    //Add elements to the array
    //
    //
    //


    return students;
    }


-(void)viewWillAppear{



  NSArray *array = [self newListOfStudents];
    self.studentsList = array;
    [array release];

    }

Assume these methods are called in the main thread itself.

Interms of memory usage , I think that the second option is good, because it does not create autoreleased objects, because they are released only at when the autorelease pool is drained.

I assume that the main autorelease pool is drained only when the app quits. So if the method in OPTION 1 is used many times ,(since they are getting called in ViewWillAppear) I think that many lists will be in autorelease pool being released only when the app quits.

So is the OPTION 2 approach the better approach?

UPDATE:

I have updated the viewWillAppear implementation for better clarity.

Was it helpful?

Solution

I think in the second example you meant to call

self.studentsList = [self newListOfStudents];

In case that studentsList is a retained property, this would leak now.

Also, that temp array in both examples is just useless overhead. In the second example it's plain nonsense.

The cleanest solution is

-(NSArray *)listOfStudents {
   NSMutableArray *list = [NSMutableArray array];
   // Add things to array
   return list;
}

Two more advices:

1) you might run the static analyzer over your code, which will point to memory issues.
2) if you feel more confident with memory management, switch over to ARC.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top