Anthony Glyadchenko
Anthony Glyadchenko

Reputation: 3622

Why would one autorelease one's own property in Objective-C?

Here's a code example to show what I mean:

- (void) setup {
  [self setupObjectModel];
  [self setupStoreCoordinator];
}

- (void) setupObjectModel {
  NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Model" withExtension:@"momd"];
  self.managedObjectModel = [[[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL] autorelease];
}

Upvotes: 0

Views: 110

Answers (1)

Olotiar
Olotiar

Reputation: 3274

In case managedObjectModelis a strongproperty or defined with attribute retain, the setter will automatically retain the passed argument, thus autoreleaseing it will prevent a memory leak (if you don't do it, the retain count of the NSManagedObjectModel will be 2 although only managedObjectModelpoints to it.)

This is equivalent to

_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];

assuming the setter has the default behaviour

Upvotes: 1

Related Questions