开发者

What type should alloc return?

开发者 https://www.devze.com 2023-01-15 06:56 出处:网络
I have a method like this which performs further initializations on other objects with similar init methods.

I have a method like this which performs further initializations on other objects with similar init methods.

- (Foo*)initWithInput:(NSMutableString*)i {
  bar = [[Bar alloc] initWithInput:input];
  return self;
}

This produces a warning "Foo.m:19: warning: incompatible Objective-C types assigning 'struct Foo *', expected 'struct Bar *'"

I am assuming the alloc method is returning an (id) type and then the compiler can't decide which initWithInput: method I want to use on the allocated object. I can of course remove the warning like this but it's not terribly pretty

开发者_运维知识库
- (Foo*)initWithInput:(NSMutableString*)i {
  bar = [((Bar*)[Bar alloc]) initWithInput:input];
  return self;
}

Is there an idiomatic way of handling this?


Is there an idiomatic way of handling this?

Objective-C has a flat namespace for selectors and does not support covariant dispatch (a la Java and C++). Thus, you need to name your methods uniquely per argumentation.

This is also the standard pattern of the frameworks. You [generally -- there are 1 or 2 exceptions] don't see two methods with the same name -- the same selector -- with different argumentation. When it does happen -- like the return value of alloc -- you'll see id used.


All init-methods should return id and not the type of the class they belong to for exactly this reason. This is actually documented by Apple somewhere. I can’t find the link at the moment, though.

0

精彩评论

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