2

I've seen this in an example-- In a class initialize, does this line have any purpose?

+(void)initialize
{
   if (self == [ToolController self])
   {
      ...
   }
}

I have read that in a class method, self refers to the class and not an object. So in theory, wouldn't this check always result in true?

In my mind, that line would resolve to this: ToolController == ToolController

So that's why I would think that it would always result in true. Am I missing something?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
A O
  • 5,516
  • 3
  • 33
  • 68
  • What would happen if there was a subclass of `ToolController`? – Darren Jun 02 '15 at 21:29
  • I am pretty sure the reason is given in the docs fot initialize. – Sulthan Jun 02 '15 at 21:31
  • The "duplicate" question is not a duplicate question. It's a slightly related question that happens to have the same answer. Duplicate questions should actually ask the same question, not just have similar answers. – rmaddy Jun 02 '15 at 22:15
  • Here's a better duplicate: http://stackoverflow.com/questions/324666/should-initialize-load-always-start-with-an-if-self-myclass-class-guar – rmaddy Jun 02 '15 at 22:17

2 Answers2

3

I think you are missing the possibility that self is a subclass of ToolController.

Presumably in the example you're reading, whatever is happening in +[ToolController initialize] should happen only when the superclass (ToolController) initializes, and not happen additionally when any subclasses of ToolController initialize.

Aaron Golden
  • 7,092
  • 1
  • 25
  • 31
  • Explained in more detail in [the documentation for `+[NSObject initialize]`](https://developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/index.html#//apple_ref/occ/clm/NSObject/initialize). – rob mayoff Jun 02 '15 at 21:33
  • Ah that makes sense, didn't realize that subclasses were calling it as well. Mostly I had a hard time forming a google query for `self == [className self]`. Cheers :) – A O Jun 02 '15 at 21:53
2

From the Apple Docs on NSObject about initialize:

The superclass implementation may be called multiple times if subclasses do not implement initialize—the runtime will call the inherited implementation—or if subclasses explicitly call [super initialize]. If you want to protect yourself from being run multiple times, you can structure your implementation along these lines:

+ (void)initialize {
  if (self == [ClassName self]) {
    // ... do the initialization ...
  }
}

As you can't assume that every subclass will overwrite the initialize method (in fact, most probably won't), it's best practice to check that the class is actually the one you're expecting.

JRG-Developer
  • 12,454
  • 8
  • 55
  • 81