Calling -init multiple times in Objective-C

后端 未结 2 2042
清酒与你
清酒与你 2021-01-05 09:01

What happens when you call -init multiple times on one object, are there some hidden side effects? Can you assume that no additional memory is allocated? Would anything go a

相关标签:
2条回答
  • 2021-01-05 09:35

    Calling -init multiple times is undefined, unsupported, and will lead to bugs, crashes, and other unexpected behavior.

    Many classes -- NSString, NSArray, and NSDictionary, for example -- don't actually allocate anything when the +alloc method is called. It isn't until one of the various -init* methods are called that the object has enough context to figure out the most efficient means of doing whatever you ask.

    0 讨论(0)
  • 2021-01-05 09:42

    One thing I'd add to Bill's answer is that when writing your own -init methods, code defensively and don't assume that they'll only be invoked once.

    0 讨论(0)
提交回复
热议问题