new in Xcode 6.3/iOS 8.3: using self alloc for convenience constructor causes build error

廉价感情. 提交于 2019-12-10 13:47:29

问题


This code did not change between Xcode 6.2 and 6.3, but the line containing [self alloc] now causes the error:

Multiple methods named 'initWithType:' found with mismatched result, parameter type or attributes

@implementation AGNetworkDataRequest

+ (instancetype)networkDataRequestWithType:(AGNetworkDataRequestType)type
{
    AGNetworkDataRequest *r = [[self alloc] initWithType:type];//error here
    return r;
}

- (id)initWithType:(AGNetworkDataRequestType)type
{
    //typical init code
}

//...

If I Cmd+click on the initWithType: call, I am shown the conflict in CAEmitterBehavior, an object not referenced in our project at all, but I'm guessing must be new in iOS 8.3.

If I change the [self alloc] to [AGNetworkRequest alloc], the subclasses inheriting this method will just return the parent object, which acts in opposition to how we designed this class.

Any way to eliminate the conflict without changing the method name (which requires changing all method calls throughout the app)?


回答1:


cast your alloc return.

[(AGNetworkDataRequest*)[self alloc] initWithType:type];

This will give the compiler enough information to make the call. If the compiler doesn't know the length of your parameter there is a chance the call will fail at runtime (and potentially be very difficult to debug).

returning instancetype rather than id is supposed to fix this (allocWithZone will automatically return instancetype...) but it's possible because you're using 'self' there is not enough static information.



来源:https://stackoverflow.com/questions/29563701/new-in-xcode-6-3-ios-8-3-using-self-alloc-for-convenience-constructor-causes-bu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!