-alloc -init of an Object Instance Variable?
-alloc -init of an Object Instance Variable?
- Subject: -alloc -init of an Object Instance Variable?
- From: Jerry Krinock <email@hidden>
- Date: Wed, 21 Jul 2004 21:18:55 -0700
I have an NSMutableArray declared as an object instance variable:
@interface MyObject : NSObject
{
// Object Instance Variables
NSMutableArray* myArray ;
...
}
Now, the only messages I ever send to myArray are: -addObject, -count and
-objectAtIndex. It works OK, despite the fact that nowhere in my program do
I ever allocate, initialize, or call any method which would "create"
myArray. This bothers me. Gee, I thought, it seems like this should be
done when initializing MyObject. So, I wrote:
@implementation MyObject
- (id)init
{
self = [super init] ;
if (self)
{
myArray = [[NSMutableArray alloc] init] ;
}
return self ;
}
And then, to my surprise, run and crash! If I comment out:
//myArray = [[NSMutableArray alloc] init] ;
then it works OK again.
From the results of this "experiment", I conclude that, when an object is
initialized, Objective-C automatically initializes its object instance
variables. But I can't confirm this in the documentation. Somewhat to the
contrary, in
file:///Developer/Documentation/Cocoa/Conceptual/ObjectiveC/index.html
I read that:
"... Every class that declares instance variables must provide an init...
method to initialize them (unless the variables require no initialization).
The init... methods the class defines initialize only those variables
declared in the class. ..."
which seems a little ambiguous. Could someone please clarify this for me?
Jerry Krinock
San Jose, CA USA
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.