开发者

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

In the following example, what are the possible problems that can开发者_Go百科 occur.

id c = [Person alloc];
[c init];


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.


When using the id generic type, you won't get a warning if you try to call a method that doesn't exist. The compiler assumes you know what you're doing.

Otherwise, no issues that I can think of. It's common in several situations (think fast enumeration on heterogeneous container type)


Another potential danger is that over time, you may add logic that accidentally only does init for certain cases... leaving an object that is allocated but never initialized means all values in it are essentially random and any setup code it was meant to do is not done.


First of all, type casting problem. Every time you want to use 'c', you may need to (Person *), i.e. typecast it.

secondly, if you have any method declared in Person, you can not call it as [c aMthod] style, you have to use, [(Person *) c aMethod].

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜