Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it not recommended to allocate and initialize with id?

In the following example, what are the possible problems that can occur.

id c = [Person alloc];
[c init];
like image 852
Matthew Bischoff Avatar asked Jul 16 '11 17:07

Matthew Bischoff


1 Answers

The main problem with the code in your example is that in some cases, the -init method returns an object that's different from the one that you created with +alloc. If that happened, then your code would be incorrect because you're not assigning the result of [c init] to c, and you'd end up working with the wrong object (and one that's not properly initialized at that). This is why the standard idiom is to always combine +alloc and -init on the same line:

id c = [[Person alloc] init];

Now, you may have written the Person class and have first hand knowledge that -init always returns the same object, but I shouldn't have to be intimately familiar with the inner workings of Person to read your code and have a sense of whether it's correct or not. Your code is "better" in the sense that anyone can tell that it's doing the right thing if you follow the usual convention.

I don't think it's horrible to declare c as type id, but it does seem silly in this case. You know that c will be of type Person*, so why declare it as id and throw away useful information that the compiler can use to help you write better code? If there's a good reason to use id, that's fine, but if you can be more specific about the type you should do so.

like image 158
Caleb Avatar answered Sep 25 '22 18:09

Caleb