神奇的方法来自哪里?

时间:2017-02-15 21:43:56

标签: objective-c xcode macos

我遵循Objective-C代码。但我不理解

  • alloc中的initCar *toyota = [[Car alloc] init];是什么?

  • 这个方法来自哪里? setModel

// Car.h

#import <Foundation/Foundation.h>

@interface Car : NSObject {
}

@property (copy) NSString *model;

- (void)drive;

@end

// Car.m

#import "Car.h"

@implementation Car {
  double _odometer;
}

@synthesize model = _model;

- (void)drive {
  NSLog(@"Driving a %@. Vrooooom!", self.model);
}

@end

// main.m

#import <Foundation/Foundation.h>
#import "Car.h"

int main(int argc, const char * argv[]) {
  @autoreleasepool {
    Car *toyota = [[Car alloc] init];

    [toyota setModel:@"Toyota Corolla"];
    NSLog(@"Created a %@", [toyota model]); // SQL: Insert into Car value 

    toyota.model = @"Toyota Camry"; // SQL: Update car set model=''
    NSLog(@"Changed the car to a %@", toyota.model);

    [toyota drive]; // SQL: Select *from Car

  }
  return 0;
}

1 个答案:

答案 0 :(得分:1)

allocinit继承自NSObject,并初始化您的新CarsetModel:自动生成@synthesize d属性model(方法model也是如此,以获取其值)。如果需要,您可以覆盖这些方法以执行额外的工作。另外:在现代Objective-C中,属性访问器(“点”)语法通常比显式调用getter / setter方法更受欢迎。