Is there any hidden side effect of initialising NSString object twice

Viewed 57

If we initialise NSString object twice then is there any issue or side effects?

NSString *str = [[NSString alloc] init];
str = [str init];
2 Answers

It is undefined behavior to call init on an already-initialized object. From the ARC documentation:

It is undefined behavior for a program to cause two or more calls to init methods on the same object, except that each init method invocation may perform at most one delegate init call.

What you are doing could crash your program or lead to data corruption. Don't do it.

The "init" method expects an object that is initialised by setting all members to 0 or nil, nothing else. Like the result of [SomeClass alloc].

Calling init twice can give you all kinds of nasty side effects. For example, if the first init allocated memory, it is highly likely that the second init will cause a memory leak. Worse things can happen. And if you don't see anything bad happening now, you can bet something bad will happen in the next MacOS or iOS version.

Related