问题
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