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: "Richard Altenburg (Brainchild)" <email@hidden>
- Date: Wed, 18 Jul 2012 08:16:23 +0200
If you create a new instance of a class, all its instance variables are zero, so any pointers to objects like strings and arrays are zero as well, they are there but do not point to anything. The instantiation does not automatically create those objects as well for you, you are responsible.
You do not need to create placeholders in the init like you do in method 1. You can wait until your code tries to access such a variable through a getter method and then check to see if it already exists. If not, you create it on the spot.
Currently you probably use @property to define your properties and @synthesize to create the getter and setter methods for them. Leave that in place, but still create your own getter method, for example foodLists, and in here first ask if it already points to an array, if not, alloc and init an array and assign this ti the instance variable. Now in the rest of your code, whenever you want to do something, like adding an item to foodLists, you can call [[self foodLists] addObject:xxxx] and this will first go through your getter method which then will check if there is a valid array already. No crash, no pain...
Just my thought...
[[[Brainchild alloc] initWithName:@"Richard Altenburg"] saysBestRegards];
Op 25 jun. 2012, om 07:48 heeft fly2never het volgende geschreven:
> Besides this two way to init instance variables, which one is the best
> practice?
> Method 1 ensure that all instance variables(properties) are initialized and
> no crash happened, but I think it's redundantly and inconvenient.
> Because like id and name. [NSString string] means nothing, I often assign a
> new value from outside, but init NSMutableArray looks necessary.
> Method 2 make no guarantee. If you need instance variables(properties),
> init it first before you use.
> what's your choice?
_______________________________________________
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