Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
465 views
in Technique[技术] by (71.8m points)

initialization - Assigning to self in Objective-C

I'm from the C++ world so the notion of assigning this makes me shudder:

this = new Object; // Gah!

But in Objective-C there is a similar keyword, self, for which this is perfectly acceptable:

self = [super init]; // wait, what?

A lot of sample Objective-C code uses the above line in init routines. My questions:

1) Why does assignment to self make sense (answers like "because the language allows it" don't count)

2) What happens if I don't assign self in my init routine? Am I putting my instance in some kind of jeopardy?

3) When the following if statement fails, what does it mean and what should I do to recover from it:

- (id) init
{
    self = [super init];

    if (self)
    {
        self.my_foo = 42;
    }

    return self;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is a topic that is frequently challenged by newcomers:

Basically, it stems from the idea that a superclass may have over-ridden the designated initializer to return a different object than the one returned from +alloc. If you didn't assign the return value of super's initializer into self, then you could potentially be dealing with a partially initialized object (because the object that super initialized isn't the same object that you're initializing).

On the whole, it's pretty rare for super to return something different, but it does happen in a couple of cases.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...