Why is it not recommended to allocate and initialize an identifier?

In the following example, what are the possible problems that may arise.

id c = [Person alloc]; [c init]; 
+7
source share
4 answers

The main problem with the code in your example is that, in some cases, the -init method returns an object other than the one you created with + alloc. If this happens, then your code will be incorrect, because you are not assigning the result [c init] to c, and you will end up working with the wrong object (and one that was not correctly initialized at the same time). This is why the standard idiom should always combine + alloc and -init on the same line:

id c = [[Facial highlight] init];

Now you may have written the Person class and gained first-hand knowledge that -init always returns the same object, but I donโ€™t need to be familiar with Personโ€™s internal work in order to read your code and whether it makes sense or not. . Your code is โ€œbetterโ€ in the sense that everyone can say that it does the right thing if you follow the usual convention.

I don't think it's terrible to declare c as a type identifier, but in this case it seems silly. You know that c will be of type Person *, so why declare it as id and throw out useful information that the compiler can use to help you write code better? If there is a good reason to use an identifier, thatโ€™s fine, but if you can be more specific by type, you should do it.

+14
source

When using the id generic type, you will not receive a warning if you try to call a method that does not exist. The compiler assumes that you know what you are doing.

Otherwise, there are no problems that I can think of. It is common in several situations (think of quickly transferring to a heterogeneous container type)

+4
source

Another potential danger is that over time, you can add logic that accidentally runs only for certain cases ... leaving an object that is selected but not initialized means that all values โ€‹โ€‹in it are essentially random, and any the installation code that he meant to do is not done.

+2
source

First of all, enter the casting problem. Each time you want to use ' c ', you may need (Person *) , i.e. His type.

secondly, if you have any method declared in Person, you cannot name it as [c aMthod] style, you should use [(Person *) c aMethod].

-one
source

All Articles