Search code examples
iphoneobjective-cclass-designrelease-managementgrand-central-dispatch

Where should I release an object? Can it release itself?


I want to get friends information from Facebook and save it with Core Data.

I build a FriendsManager Class that gets the a list of friends from Facebook (name and id) and a FriendInfo Class that takes the id and gets all the info about this friend.

I thought I'd do it this way:

  • Create an object of FriendsManager let it get all my friends (not really a problem);
  • in the FriendsManager create an instance of FriendInfo;
  • give it the id and let it get all the info I need including geocoding of hometown;
  • save all this with core data.

But then where do I release this object?

In Order to get all the friends info I would create these objects in an loop that goes through my Array with friend ID's.

I also do all the getting info & geocoding with Grand Central Dispatch so do not really know when a FriendInfo got all the data it needs and is ready.


Solution

  • A Core Data object is usually a subclass of NSManagedObject, not a NSObject. You don't alloc or release it, you create one with the ManagedObjectContext and you either save or delete it but you don't release it because you don't own it.

    A NSObject (prior to ARC) follows the usual rules of memory management - simply, if you get it through alloc, copy or a method starting with new, it is yours and you need to use release when you no longer use it. If you get it without allocating it - for example "NSString *string = [NSSTring stringWithFormat:@"test"]; then it is autoreleased and you don't need to release it.

    Trust the analyser - shift-command-B.

    Sounds like you might want to define your core data model and then create a NSManagedObject subclass for the friends information. You would create it using something like [NSEntityDescription insertNewObjectForEntityForName:@"FriendInfo" inManagedObjectContext:moc]; rather than [[FriendInfo alloc] init] as you would if it were a NSObject. The shift in thinking is that the object is created and managed by the ManagedObjectContext before you put any data in there, you request a new one and put in the data, then inform the ManagedObjectContext what you want done with that object - save or rollback (reverse all changes since the last save).