1. 程式人生 > 實用技巧 >OC的getter和setter方法

OC的getter和setter方法

公司業務需要轉ios,學習一下

OC中get方法函式名一般直接命名為對應的例項變數(成員變數)名字,setter方法的函式名為set加例項變數名字,注意駝峰命名。

main.m:

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

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        Car *myFirstCar = [Car new];
        Body* body;
        Body
* newBody = [Body new]; [myFirstCar setBody: newBody]; } return 0; }

myFirstClass.h:

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

#import <Foundation/Foundation.h>

@interface Tire : NSObject

-(void) print;
@end

@interface Body : NSObject
-(void) print;
@end

@interface Car : NSObject
{
    Tire
* tires[4]; Body* body; } -(Body *) body; -(void) setBody:(Body*) newBody; -(void) print; @end

myFirstClass.m:

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

#import "MyFirstClass.h"

@implementation Tire

-(void) print {
    NSLog(@"%s","Tire");
}

@end

@implementation
Body -(void) print{ NSLog(@"%s","Body"); } @end @implementation Car -(Body*) body{ return body; } -(void) setBody:(Body*) newBody{ body = newBody; } -(id) init { if(self = [super init]) { for(int i = 0; i< 4; ++i) { tires[i] = [Tire new]; } body = [Body new]; } return self; } -(void) print{ for(int i=0;i<4;++i) { [tires[i] print]; } [body print]; } @end