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

1

5

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)?

Headboard answered 10/4, 2015 at 14:12 Comment(4)
Your initWithType: method should return instancetype, not id. Make sure all of your init... methods are declared with instancetype.Toxinantitoxin
@Toxinantitoxin Apple APIs seem to follow the pattern of id for init and instancetype for convenience constructors. Do you have a link to Apple docs stating all inits should be instancetype?Headboard
Look at the docs for just about any init... method and see that it returns instancetype. For example: UITableView initWithFrame:style: or NSArray init. All of the id return types for init... methods was changed to instancetype by Apple in some recent iOS update (I forget which one).Toxinantitoxin
@Toxinantitoxin Noted. Unfortunately, changing the init return type to instancetype does not fix the issue.Headboard
H
5

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.

Hines answered 10/4, 2015 at 17:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.