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: Uli Kusterer <email@hidden>
- Date: Wed, 18 Jul 2012 10:27:15 +0200
On 18.07.2012, at 09:09, Lee Ann Rucker wrote:
> In init, and only when they need it. They're all initialized to nil, which is a perfectly reasonable value for an instvar to have; there's very rarely a reason to do anything like
>
> fly2never wrote:
>> name = [NSString string];
>
> because sending a method to nil is perfectly safe, unlike C++.
Ah! No! That's not a blanket guarantee! It is only valid for methods that return void, integer types or pointers. If your method returns a struct and you send it to NIL, you get garbage back.
>> it crashes.
If you are not using ARC, I could see why the first code sample crashes ([NSString string] returns an object you do not own -- either retain it, or use [[NSString alloc] init] instead, otherwise it gets released and your instance variable contains the address of an object that is long gone, and you'll crash when you next try talking to it).
> Besides this two way to init instance variables, which one is the best
> practice?
In general, I would recommend sticking with initializing everything in -init unless you have a good reason (e.g. if you need to refer to an external object that also needs to know about your object, you have to create one first, before you can have the other one reference it, so obviously you can't do that until -init has returned). But premature optimization is the root of all evil. So better set up everything so you're sure it's correct.
That's one major advantage of objects: They encapsulate their own behavior, so people who actually use them don't have to know about their internal workings too much. The object just "does the right thing" by default, and you only change the values that you need differently.
Similarly, as others have written, don't just give the client of your object your mutable array. Give them methods to add to and remove objects. That way, your object can actually know whether someone just looked at your objects, or changed them. You may have an internal cache later, and when someone changes the array, you have to know about it so you can remove a deleted object from the cache etc.
Cheers,
-- Uli Kusterer
"The Witnesses of TeachText are everywhere..."
http://www.masters-of-the-void.com
_______________________________________________
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