开发者

Is this the correct way to reloadData on a UITableView?

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.it开发者_如何学编程ems];

        //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];


try

[tableView reloadData];

in the viewWillAppear method....


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];


If you're using CoreData, then ideally you should be using a NSFetchedResultsController to manage the data for the tableview. (You did ask for the "correct" way :-)

You'll end up with a more memory efficient app.

See the iPhoneCoreDataRecipes Sample for a good example

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜