A question regarding object release
The below code is from Apple's GKRocket iPhone demo app:
- (void) peerListDidChange:(SessionManager *)session;
{
NSArray *tempList = peerList;
peerList = [session.peerList copy];
[tempList release];
[self.tableView reloadData];
}
I am new to objective c and was wondering if tempList really need to be release? My instinct and tells me is not because it did not retain the pointer. Maybe I am not seeing the whole picture.
If it does require a release, can someone with more experience please explain 开发者_StackOverflowwhy?
Thanks!
Just a guess. I haven't used that sample project before.
A new pointer to the old peerList
array is created, called tempList
:
NSArray *tempList = peerList;
The code makes a copy of session.peerList
and assigns the peerList
pointer to that new copy:
peerList = [session.peerList copy];
The old peerList
, which is actually now pointed to by tempList
, can then be released safely:
[tempList release];
If you had assigned [session.peerList copy];
right away, the old array would have no more retained pointers left, and if it wasn't autoreleased it would be a memory leak.
If you had assigned tempList
but not released it, it leaks memory for the same reason, but the purpose of tempList
is purely so the program knows what to release when you call release
anyway.
The latest version of this project actually crashes at this point in the code. session.peerList is NSMutableArray - and the app crashes when it tries to assign it to tempList. I modified the code to stop the crash. This is the declaration for peerList:
@interface GameLobbyController : UITableViewController <UITableViewDelegate, UITableViewDataSource, SessionManagerLobbyDelegate, UIAlertViewDelegate> {
NSMutableArray *peerList;
UIAlertView *alertView;
SessionManager *manager;}
This is the new version of the peerListDidChange method:
- (void) peerListDidChange:(SessionManager *)session;{
peerList = session.peerList;
[self.tableView reloadData];}
Not sure, but I think all that tempList code was simply to handle the switch from mutable to fixed array. Obviously I don't understand why it was so important for the peerList property to be fixed rather than mutable. All comments welcome.
精彩评论