I have a class Monkey like this:
@interface Monkey : NSObject
{
  NSString *name;
  NSMutableArray *foodLists;
  NSString *id;
  int age;
}

@property blah blah.........

my init method looks like this:
Method 1
- (id)init
{
  if ((self = [super init])) {
    name = [NSString string];
    foodLists = [NSMutableArray array];
    id = [NSString string];
  }
  return nil;
}

So when I call Monkey *m1 = [[Monkey alloc] init];
I can use it directly. [m1.foodLists addObject:foo]; and everything goes
fine.

But if my init method like this :
Method 2
- (id)init
{
  if ((self = [super init])) {
    // do nothing, leave instance variables uninitialized.
  }
  return nil;
}

Then I call Monkey *m1 = [[Monkey alloc] init];
and I call [m1.foodLists addObject:foo]; , it crashes.
I must use m1.foodLists = [NSMutableArray array]; and [m1.foodLists
addObject:foo];

====================================
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? Comments welcome : )
_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

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:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to