ObjC: proper use of property and synthesize?

冷暖自知 提交于 2020-06-09 05:31:08

问题


Does anyone know why this code is running into compilation errors? I'm compiling it on Catalina using clang. I posted a similar issue here but that was when I was trying to compile using clang on Linux. I thought getA and setA are auto-generated by synthesize. Thanks!

#import <Foundation/Foundation.h>

@interface A: NSObject

@property int a;

@end

@implementation A
{
    int a;
}
@synthesize a;

@end

int main (int argc, char * argv[])
{
  @autoreleasepool {
    A *a = [[A alloc] init];

    [a setA:99];
    int v = [a getA];
    NSLog (@" %d\n", v);
  }
  return 0;
}

Compilation:

$ clang -framework Foundation otest0.m -o hello
otest0.m:23:16: warning: instance method '-getA' not found (return type defaults
      to 'id') [-Wobjc-method-access]
    int v = [a getA];
               ^~~~
otest0.m:3:12: note: receiver is instance of class declared here
@interface A: NSObject
           ^
otest0.m:23:9: warning: incompatible pointer to integer conversion initializing
      'int' with an expression of type 'id' [-Wint-conversion]
    int v = [a getA];
        ^   ~~~~~~~~
2 warnings generated.

回答1:


The getter/setter pair is synthesized as

-(int)a;
-(void)setA:(int)val;

So you need:

int main (int argc, char * argv[])
{
  @autoreleasepool {
    A *a = [[A alloc] init];

    [a setA:99];
    int v = [a a];
    NSLog (@" %d\n", v);
  }
  return 0;
} 



回答2:


Declaring a property with name a produces a getter with name a, not getA. This is what the first warning is about: "instance method '-getA' not found"




回答3:


This works on my system (macOS):

#import <Foundation/Foundation.h>

@interface A: NSObject

@property int a;

@end

@implementation A {
  int a;
}
@synthesize a;

-(int) getMyValue {
return a;
}

@end

int main () {
  @autoreleasepool {
    A *a = [[A alloc] init];
   [a setA:99];
   NSLog (@"value = %d", [a getMyValue]);
 }
  return 0;
}

If file is saved as synth.m the terminal command is: clang synth.m -framework Foundation -o synth && ./synth



来源:https://stackoverflow.com/questions/61990028/objc-proper-use-of-property-and-synthesize

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