A call - several times in Objective-C

What happens if you call several times on the same object, are there any hidden side effects? Can you assume that no extra memory is allocated? Will anything go against such an idea?

+7
objective-c cocoa
source share
2 answers

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

Many classes - NSString , NSArray and NSDictionary , for example - do not actually allocate anything when calling the +alloc method. Only one of the various -init* methods is invoked that the object has enough context to figure out the most efficient ways to do whatever you ask.

+31
source share

One thing I would add to Bill’s answer is that when writing your own -init methods -init protect the code and don’t assume that they will be called only once.

+3
source share

All Articles