Objective-C protocol property compiler warning

旧城冷巷雨未停 提交于 2019-12-13 05:54:35

问题


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:

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


回答1:


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);
    }
}



回答2:


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.



来源:https://stackoverflow.com/questions/11310121/objective-c-protocol-property-compiler-warning

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