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

 

posted @ 2020-11-24 21:20  NeoZy  阅读(263)  评论(0编辑  收藏  举报