对象:正确使用属性并进行合成? [英] ObjC: proper use of property and synthesize?

查看:83
本文介绍了对象:正确使用属性并进行合成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道为什么这段代码会遇到编译错误吗?我正在使用clang在Catalina上进行编译。我在此处发布了类似的问题,那是我尝试使用在Linux上发出叮当声。我以为getA和setA是由synthesize自动生成的。谢谢!

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

编译:

$ 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.


推荐答案

getter / setter对合成为

The getter/setter pair is synthesized as

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

所以您需要:

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

这篇关于对象:正确使用属性并进行合成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆