Best way to set a saved property for a newly created object

What is the best way to cope with the creation of an object for living in a saved property? I have given some examples.

Assume the property:

@property (nonatomic, retain) myProperty; @synthesize myProperty = _myProperty; 

Option 1:

 self.myProperty = [[[MyClass alloc] init] autorelease]; 

Option 2:

 self.myProperty = [[MyClass alloc] init]; [self.myProperty release]; 

Option 3:

 _myProperty = [[MyClass alloc] init]; 

Option 4:

 MyClass *property = [[MyClass alloc] init]; self.myProperty = property; [property release]; 
+5
source share
4 answers

Option 1: Acceptable ... but you're wasting resources on auto-advertising. The link is added to the list of elements that should be released at the end of the loop ... your variable remains until it is needed .. etc. Etc. I find this option often used ... but I also find it lazy and wasteful.

Option 2: Confused. There is nothing wrong with that, but I would say that it is a bad form.

Option 3: Acceptable, but not perfect. What if there is a custom setter? Etc. I personally would use this form only in my own custom device or, possibly, in the class initializer. Otherwise, you lose some of the benefits of the properties.

Option 4: Best.

+4
source

If when initializing an object that contains a variable:

1) no. this is a bad form for invoking accessories in partially constructed states (e.g. init , dealloc )

2) no. this is a bad form for invoking accessories in partially constructed states (e.g. init , dealloc )

3) right.

Exception: If your ivars are not private and you are subclassing the type declaring the property, then you should also check if the parent class has initialized the property. it is best to make properties private or not directly accessible to subclasses.

4) no. this is a bad form for invoking accessories in partially constructed states (e.g. init , dealloc )

When you are working with a fully constructed instance:

1), this is normal if readbaility is more important than keeping heap sizes low.

2) bad. the object returned from the receiver is not necessarily the object that you assigned.

3) Bad. leakage may occur if _myProperty not nil .

4) best

+5
source
 self.myProperty = [[MyClass alloc] init]; 

Use ARC to create your releases and save during compilation.

+4
source

Option 1 is correct.

Option 2 is absolutely wrong. You never call -release based on the results of accessing the resource.

Option 3 completely excludes properties. This is indeed correct in your -init method, but in other methods it is better to use a property setting tool if you have no good reason to avoid it.

Option 4 is also correct, although it is more detailed than option 1. Your call.

Edit : I read your option 4 incorrectly.

+2
source

All Articles