Re: Initializing an Array
Re: Initializing an Array
- Subject: Re: Initializing an Array
- From: Bob Savage <email@hidden>
- Date: Mon, 28 Jan 2002 20:58:45 -0600
on 1/28/02 4:17 PM, jgo wrote:
>
>
If I wasn't able to set up "self" then why bother to [super init]?
>
Then, I'd just return nil and have done with it.
You seem to have a fundamental misunderstanding here. if [super init] fails,
we don't bother with our subclass' init method.
>
So, perhaps
>
Fred * george = [[Fred alloc] init];
>
if (george != nil)
>
{
>
Fred * superResult = [super init];
>
if (superResult != nil)
>
{
>
}
>
else
>
{
>
}
>
}
>
else
>
{
>
return nil;
>
}
No, no, no! 8^0 This is not the way to do this. You don't seem to understand
what classes are. "super" is going to mean the superclass of whatever class
this code is being called in, not the class Fred.
You should be doing it like this:
// init
-(id)init {
// first assign the result of [super init] to self
if (self = [super init]) {
// only if self is not nil do we do our subclass' init
x = [[SomeClass alloc] init]; // for example
}
return self; // we return self which might be nil
}
>
Class methods are often concerned, not with the class object, but with
>
instances of the class. For example, a method might combine allocation
>
and initialization of an instance:
>
+ (id)newRect
>
{
>
return [[self alloc] init];
>
}
This is a completely different thing. Notice the '+' sign. This is
important. It means this is a Class method. Notice that it says "self" not
"super". This is a convenience constructor, not an example of how to
override instance initialization.
>
C H A P T E R 5
...
>
- initWithName:(char *)string
>
{
>
if ( self = [super init] ) {
>
name = (char *)NSZoneMalloc([self zone],
>
strlen(string) + 1);
>
strcpy(name, string);
>
return self;
>
}
>
return nil;
>
}
>
The message to super chains together initialization methods in all
>
inherited classes. Because it comes first, it ensures that superclass
>
variables are initialized before those declared in subclasses.
Exactly. Notice that this does not show alloc being called inside the init
method.
Bob