OC--@property和@synthesize关键字

//
//  MyFirstClass.h
//  Hello Objective-C
//
//  Created by admin on 2020/11/16.
//

#import <Foundation/Foundation.h>

@interface Car : NSObject

@property int x,y;

-(void) printx;
-(void) printy;

@end


//
//  MyFirstClass.m
//  Hello Objective-C
//
//  Created by admin on 2020/11/16.
//

#import "MyFirstClass.h"

@implementation Car
-(void) printy{
    NSLog(@"%d", _y);
}

-(void) printx{
    NSLog(@"%d", _x);
}

@end

在interface中对成员变量指定@property关键字,系统在编译的时候会自动加上get和set方法,但注意变量名会转化为带下划线的:x-->_x

如果不想要下划线 在implementation中加上@synthesize关键字即可:

//
//  MyFirstClass.h
//  Hello Objective-C
//
//  Created by admin on 2020/11/16.
//

#import <Foundation/Foundation.h>

@interface Car : NSObject

@property int x,y;

-(void) printx;
-(void) printy;

@end


//
//  MyFirstClass.m
//  Hello Objective-C
//
//  Created by admin on 2020/11/16.
//

#import "MyFirstClass.h"

@implementation Car
@synthesize x,y;
-(void) printy{
    NSLog(@"%d", y);
}

-(void) printx{
    NSLog(@"%d", x);
}

@end

 

posted @ 2020-11-26 11:33  NeoZy  阅读(88)  评论(0编辑  收藏  举报