I've been doing it religiously for a couple of years now. Checking for the validity of self
after calling [super init...]
methods:
self = [super init];
if (self != nil) {
// initialize
}
return self;
You can do this in a variety of ways, as this question nicely sums up, but that question is about syntax, mine is about the concept.
I recently got a question from a colleague who's learning Objective-C and he asked me "why should I test for the existence of self, isn't it obvious that it's there?" and my short answer was "err, yeah, well there's instances where it can fail, so that's why." But the long answer is that I really don't understand myself why we test for it everywhere, when the instances where it could fail are very rare. Apple's reference guide tells us about some specific cases, like when initializing with files or when dealing with singletons. But these sound like very rare exceptions to the rule that [super init]
s should just work.
So my question to you is this: Why do we always test the validity of self? Are we just implementing it everywhere to catch that one exception where it occurs? Why not just skip the whole if (self)
thing and initialize our object if the chances of it succeeding are 100% (or is that never the case)?
P.S. I realize this question must be a dupe since it's so basic, but my search queries got a lot of other questions about the syntax of initialization. Dupe links are appreciated, cheers!