OC development-@property and @synthesize (26)

I. Overview

  • @property can automatically generate setter and getter declarations for a member variable in the class .h file
  • @synthesize can automatically generate the setter and getter of a member variable in the class .m file
  • @property and @synthesize are the new features of xcode in order to simplify the writing of classes

Two-action demonstration

2.1 Person.h header file definition (@property)

#import <Foundation/Foundation.h>

@interface Person : NSObject
{
    int _age;
    int age;
    int _height;
    double _weight;
    NSString *_name;
}
@property int age;
@property int height;
@property double weight;
@property NSString *name;

-(void)test;
@end

2.2 Person.m file definition (@synthesize)

#import "Person.h"

@implementation Person
@synthesize age=age;
@synthesize height=_height;
@synthesize weight=_weight;
@synthesize name=_name;

-(void)test
{
    NSLog(@"age=%d,_age=%d",age,_age);
}
@end

2.3 main.m entry file call

 Person *person=[Person new];
 [person setAge:10];
 [person test];

2.4 Summary

2.4.1 @property

  • Used in @interface

  • Used to automatically generate setter and getter declarations

  • Use @property int age; you can replace the following two lines

    -(void)setAge:(int)age;//setter
    -(int)age; //getter
    

2.4.2 @synthesize

  • Used in @implementation

  • Used to automatically generate setter and getter implementations

  • Use @synthesize age = _age; it can be replaced

    -(void)setAge{_age=age;};
    -(int)age}{return _age};
    

Three omit the writing of member variables

3.1 Declaration and implementation

//声明
#import <Foundation/Foundation.h>
@interface Car : NSObject
@property int speed;
@property int wheels;
@end

//实现
#import "Car.h"
@implementation Car
@synthesize speed=_speed;
@synthesize wheels=_wheels;
@end

3.2 Method call

  Car *car=[Car new];
  car.speed=100;
  NSLog(@"Car的速度是%d",car.speed);

3.3 Description

  • In the implementation, @synthesize speed=_speed;the member variable _speed will be accessed. If it does not exist, the _speed variable of type @private will be automatically generated.

Four @property alternative to @property and @synthesize usage

4.1 Code (Dog.h, do not modify Dog.m file)

#import <Foundation/Foundation.h>
@interface Dog : NSObject
@property int age;
@end

4.2 File transfer (normal output)

 Dog *dog=[Dog new];
 dog.age=5;
 NSLog(@"Dog的年龄是%d",dog.age);
Published 362 original articles · 118 praises · 530,000 views

Guess you like

Origin blog.csdn.net/Calvin_zhou/article/details/105373481