Kovasandra
Kovasandra

Reputation: 555

Objective-C protocol property compiler warning

I can't get rid of compiler warning when I define property inside protocol. Strange thing is that I have two properties defined, and I only get warnings for the second one (which is object type, while the first property is value type).

Here is screenshot:

compiler warning

Can anyone tell me how to get rid of this warning, and why it is generated? The code is working normally, it is just this warning that annoys me :)

Upvotes: 0

Views: 402

Answers (2)

Enrique
Enrique

Reputation: 126

In your program, the property is called view. There must be a getter called view and a setter called setView. If you do not use @synthesize you must supply these two methods, and this is the reason of the compiler warning. The code is working normally because you do not reference the property using dot notation or call the getter and setter methods.

Upvotes: 2

Richard J. Ross III
Richard J. Ross III

Reputation: 55533

Your issue is that the compiler cannot find an implementation for the properties you defined in the protocol.

For this reason, it is not recommended to add properties to a protocol, instead, you would define just a simple method to access the property, and one to set it. That would give you the proper error messages, and while you couldn't use dot-notation, it keeps the warnings in the right place.

Alternatively, you could do something like this (not recommended, but for educational reasons):

#import <objc/runtime.h>

@protocol myProto

@property (assign) int myProperty;

@end

@implementation NSObject(myProto)

-(int) myProperty
{
    return [objc_getAssociatedObject(self, "myProperty") intValue];
}

-(void) setMyProperty:(int) myProperty
{
    objc_setAssociatedObject(self, "myProperty", [NSNumber numberWithInt:myProperty], OBJC_ASSOCIATION_RETAIN);
}

@end

@interface MyObj : NSObject<myProto> 

@end

@implementation MyObj

@dynamic myProperty;

@end

int main(int argc, char *argv[])
{
    @autoreleasepool
    {
        MyObj *myObj = [MyObj new];

        myObj.myProperty = 10;

        NSLog(@"%i", myObj.myProperty);
    }
}

Upvotes: 0

Related Questions