Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ARC Semantic Issue with simple protocol example?

I have just been trying something out with a quick test and I have a question, in the following code:

@protocol stuffieProtocol <NSObject>
@required 
-(void)favouiteBiscuit;
@end

.

// DOG & TED ARE IDENTICAL, THEY JUST LIKE DIFFERENT BISCUITS
@interface Dog : NSObject <stuffieProtocol>
@property (strong, nonatomic) NSString *name;
@end

@implementation Dog

- (id)init {
    return [self initWithName:@"Unknown"];
}

- (id)initWithName:(NSString *)name {
    self = [super init];
    if(self) {
        _name = name;
    }
    return self;
}

- (void)whoAreYou {
    NSLog(@"MY NAME IS: %@ I AM A: %@", [self name], [self class]);
}
- (void)favouiteBiscuit {
    NSLog(@"FAVOURITE BISCUIT IS: Costa Jam Biscuit");
}
@end

.

Dog *stuffie_001 = [[Dog alloc] initWithName:@"Dog Armstrong"];
Ted *stuffie_002 = [[Ted alloc] initWithName:@"Teddy Sullivan"];

NSArray *stuffieArray = @[stuffie_001, stuffie_002];
for(id<stuffieProtocol> eachObject in stuffieArray) {
    [eachObject whoAreYou]; // << ERROR
    [eachObject favouiteBiscuit];
}

My question is I am getting an error "ARC Semantic Issue: No known instance method for selector 'whoAreYou'"

If I prefix [eachObject whoAreYou]; with [(Dog *)eachObject whoAreYou]; then this works for all the iterations of the loop, but that just feels wrong as the all the objects in the array are not of type Dog.

What should I be prefixing this with to be correct?

like image 473
fuzzygoat Avatar asked Jun 24 '26 18:06

fuzzygoat


1 Answers

Add

-(void) whoAreYou;

to your protocol. Then the compiler knows that eachObject in the loop responds to that method.

like image 92
Martin R Avatar answered Jun 26 '26 09:06

Martin R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!