Re: do you init your instance variables in init method or outside the class?
Re: do you init your instance variables in init method or outside the class?
- Subject: Re: do you init your instance variables in init method or outside the class?
- From: Graham Cox <email@hidden>
- Date: Wed, 18 Jul 2012 15:09:07 +1000
On 25/06/2012, at 3:48 PM, fly2never wrote:
> Besides this two way to init instance variables, which one is the best
> practice?
Of course you initialize your instance variables in -init - THAT IS WHAT IT IS FOR!
It's very bad practice to let code outside the object set up ivars, because those ivars are an implementation detail of the object and are of no business to anyone else.
You are also not following correct memory management of the objects you assign to your ivars in the examples you give (though if you are using ARC that might be OK).
You can assign ivars lazily under some circumstances if there's some advantage to do so, for example, if your object has an -addFoo: method, and internally it uses an NSMutableArray to store them, you can create the array then, if needed, rather than in init. But there's usually not a great reason to do that.
The other thing your code is doing pretty incorrectly is exposing the internal storage of the class. You don't ask your object for a mutable array, then call -addObject: on that array. You declare a method on your class that adds the object and that can call -addObject on the internal mutable array (or anything else if it decides to change the way it stores things).
--Graham
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden