views:

31

answers:

2

I am trying to append objects to my data source and then reload the table. Is this the correct way of approaching it?

self.items is my datasource

//Copy current items
        self.itemsCopy = [self.items mutableCopy];//[[NSMutableArray alloc] initWithArray:self.items copyItems:NO];

        NSLog(@"Copy Size before append: %d",[itemsCopy count]);

        //Get new items
        int lastMsgID = [self getLastMessageID];
        [self.coreData getMoreMessages:self.title lastID:lastMsgID]; //This will update self.items with 30 objects

        //Append new items
        [itemsCopy addObjectsFromArray:self.items];

        //Empty items and copy itemsCopy
        [self.items removeAllObjects];
        self.items = [self.itemsCopy mutableCopy];

        NSLog(@"Actual Size after append: %d",[self.items count]);

        //Reload data
        [tableView reloadData];
A: 

Yes, looks about right to me.

Depending on how your properties are declared, you may have some memory issues here. If your properties specify retain as an attribute, then setting assigning a copy of an array to them will result in a retain count of 2 on the object rather than the intended 1.

Eg.

self.myProperty = [myArray mutableCopy];

mutableCopy returns a newly allocated object with a retain count of one. The caller owns this object and is responsible for releasing it. Then you assign it to your property which retains it, increasing the retain count to 2. The object will be leaked when the owner is deallocated because the property will only be released once.

The solution would be to release the mutable copy after assigning and retaining it to to the property like this.

self.myProperty = [myArray mutableCopy];
[self.myProperty release];

Alternatively you could auto release the result of mutableCopy. However there seems to be some controversy surrounding the usage of autorelease on the iPhone. I personally don't see a problem with it unless it's used in a tight loop that iterates many many times in a short period of time.

self.myProperty =[[myArray mutableCopy] autorelease];
Jasarien
+1  A: 

try

[tableView reloadData];

in the viewWillAppear method....

makboney