-2

I have follow Objective-C code. But i am not understanding

  • what is alloc, init in Car *toyota = [[Car alloc] init];?

  • from where this method came from? 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;
}
weston
  • 54,145
  • 21
  • 145
  • 203

1 Answers1

0

alloc and init are inherited from NSObject, and they initialize your new Car. setModel: is auto-generated from your @synthesized property model (and so is the method model, to get its value). You can override these methods to do extra work if you want. Also: in modern Objective-C, the property accessor ("dot") syntax is usually preferred over explicitly calling getter/setter methods.

saagarjha
  • 2,221
  • 1
  • 20
  • 37