【发布时间】:2020-05-23 21:59:06
【问题描述】:
我正在尝试正确使用@property 和@sythesize,但遇到了这些错误。有谁知道这段代码有什么问题?这看起来应该如何使用,但编译不正确。
谢谢!
#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;
}
clang-7 -o a.out otest1.m -I `gnustep-config --variable=GNUSTEP_SYSTEM_HEADERS` -L `gnustep-config --variable=GNUSTEP_SYSTEM_LIBRARIES` -lgnustep-base -fconstant-string-class=NSConstantString -D_NATIVE_OBJC_EXCEPTIONS -lobjc && ./a.out
otest1.m:12:13: error: synthesized property 'a' must either be named the same as a
compatible instance variable or must explicitly name an instance variable
@synthesize a;
^
otest1.m:22:16: warning: instance method '-getA' not found (return type defaults to 'id')
[-Wobjc-method-access]
int v = [a getA];
^~~~
otest1.m:3:12: note: receiver is instance of class declared here
@interface A: NSObject
^
otest1.m:22:9: warning: incompatible pointer to integer conversion initializing 'int' with
an expression of type 'id' [-Wint-conversion]
int v = [a getA];
^ ~~~~~~~~
2 warnings and 1 error generated.
411 [debian:~/src/c]$
更新: 解决方案是 @synthesize 创建方法 setA 和 a。不是 setA 和 getA。我对此感到困惑,但这似乎是编译中的问题。我在 Mac OS Catalina 上使用 clang 并在 Linux 上使用 clang 测试了解决方案 here,它可以工作。
【问题讨论】:
-
@jtbandes 根据该帖子中的建议,我在实施部分声明了“int pa”,但错误仍然存在。
-
或许可以试试
_pa?还是@synthesize pa=pa;?顺便说一句,您的主要功能是错误的,您的意思可能是[a setPa:99]而不是[A setPa:99]。 -
@jtbandes 更新了代码,同样的错误。您是否认为这是名称空间冲突 re: _pa?
-
@Willeke 我无法输入 { int a; } 在用大括号实现。我必须把它放在没有大括号的实现下才能编译。
标签: objective-c