Three Objective-C Constructor Questions

I have three quick questions that I have encountered conflicting answers to which I hope someone can clarify.

  • Do I need to execute [super init] before NSObject to the end? (for example, if Foo inherits from NSObject, should Foo call [super init]? If not, does this also apply to dealloc?
  • Whether some form of initialization occurs by default for member variables in the object. For example, would the NSString * element be initialized to nil? float to 0.0?
  • If my object has an initFoo method, can I call [self init] inside this function to perform general initialization?

Since I start with Objective-C, I quite often accept Yes for the first and No for the second two, but I hope to keep some typings :)

Thank,

+3
source share
4 answers

Just add a little more to the three answers ahead:

  • Yes Yes. In practice NSObject(maybe) it does not require it (now), but if it ever changes, you will be screwed up if you do not. It's best to get into the habit (or use code generation in Xcode to remove the initialization pattern). However, it is not always initthat you should call (rather).

  • As noted, the default initialization (by virtue of memcpy 0s, so 0, nil, etc.) is guaranteed, and it is reasonable to rely on this idiomatically. Some people still prefer to be explicit and beautiful.

  • . init, . ( ). , . , , " ", . . , ? init - , , , , , .

() , Apple.

+6

self. super -dealloc.

/, .

, [self init] :

- (id)initFoo
{
    self=[self init];
    if(self)
    {
       //do stuff
    }
    return self;
}
+2
  • yes init ( , ) dealloc
  • , 0, nil, 0.0 ..
  • , .
0
  • , .

  • .

  • . init, . . init: .

0

Source: https://habr.com/ru/post/1732491/


All Articles