0

Is it safe in Objective-C to write

self.propery = [[SomeClass alloc] init];

instead of

SomeClass *tmp = [[SomeClass alloc] init];
self.property = tmp;
[tmp release];

or will the first form leak memory?

giorgiga
  • 1,758
  • 12
  • 29
  • 1
    Show us the property declaration for "property". That's the `@property` line. – jer Aug 23 '10 at 16:39

4 Answers4

5

The first example leaks unless you provide a custom property setter. You can use:

self.propery = [[[SomeClass alloc] init] autorelease];

Instead.

Kevin Sylvestre
  • 37,288
  • 33
  • 152
  • 232
  • Thanks. Won't that keep memory until the NSAutoreleasePool is released (ie by default, until I exit the application)? – giorgiga Aug 23 '10 at 17:08
  • My understanding is that the autorelease pool will typically be released after each execution of the 'run loop' (before the exit of the application). This is assuming you are writing a Cocoa or Cocoa Touch application. – Kevin Sylvestre Aug 23 '10 at 19:05
2

It depends on how the property is defined. If it's defined with retain or copy then, yes, your first example will leak.

Stephen Darlington
  • 51,577
  • 12
  • 107
  • 152
  • If the @propriety is with assign, then it will not leak. That's true. However, it's the responsibility of the propriety to retain the value if it wants to use it later (not where you set it). – gcamp Aug 23 '10 at 16:46
  • Property has "retain". I kinda hoped there was a way to assign a new object to a property without temporary variables - I'm too much used to work with a garbage collector, probably (no, I don't want that in my app - if I'm going to learn Objective-C I'll better swallow it as it is). Thanks – giorgiga Aug 23 '10 at 17:02
0

The first one will leak.

You must release or autorelease anything you [[ alloc] init] when you don't need it anymore.

Refer to this guide.

gcamp
  • 14,622
  • 4
  • 54
  • 85
0

It doesn't make a bit of difference whether or not your property is defined as retain, copy, or assign. When you create a local instance of a class with [[SomeClass alloc] init], you are responsible for releasing it within the scope it was created.

Kevin's response is correct. If you do not feel like creating, setting, releasing - you can use autorelease. The main autorelease pool is drained from time to time, you will not be using that memory for the lifetime of the application.

It is worth noting that the unpredictable nature of autorelease pools means that you can not be sure when that memory will be released. If working in a memory constrained platform like the iPhone, you should avoid using autorelease except in places where necessary.

Jerry Jones
  • 5,393
  • 2
  • 22
  • 14