ObjC: proper use of property and synthesize?

前端 未结 3 1556
迷失自我
迷失自我 2021-01-29 04:06

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 c

相关标签:
3条回答
  • 2021-01-29 04:21

    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"

    0 讨论(0)
  • 2021-01-29 04:29

    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

    0 讨论(0)
  • 2021-01-29 04:32

    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;
    } 
    
    0 讨论(0)
提交回复
热议问题