天天看点

Objective-C 面向对象基础-构造方法

OC中的类使用的是两段的构造方法,这与通常的C++和Java不同,如果想通过构造的方式传递参数,可以重载一个init方法,下面贴代码。

//
//  Goods.h
//  04_Description
//
//  Created by apple on 14-11-9.
//  Copyright (c) 2014年 cc. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Goods : NSObject {

    int _price;
    int _count;
    
}

/**
 *  多参的构造方法
 *
 *  @param price 价格
 *  @param count 数量
 *
 *  @return 当前类的对象
 */
- (id)initWithAttribute:(int)price:(int)count;

- (void)setPrice:(int)price;
- (int)price;

- (void)setCount:(int)count;
- (int)count;

@end
           
//
//  Goods.m
//  04_Description
//
//  Created by apple on 14-11-9.
//  Copyright (c) 2014年 cc. All rights reserved.
//

#import "Goods.h"

@implementation Goods

/**
 *  多参的构造方法
 *
 *  @param price 价格
 *  @param count 数量
 *
 *  @return 当前类的对象
 */
-(id)initWithAttribute:(int)price :(int)count {
    //需要调用父类(super)的构造来初始化当前类的对象
    self = [super init];
    if (self) {
        //给成员属性赋值
        _price = price;
        _count = count;
    }
    
    // id类型可以代表任意类型的对象,这里是返回当前类的对象
    return self;
}

-(void)setPrice:(int)price {
    _price = price;
}

-(int)price {
    return _price;
}

-(void)setCount:(int)count {
    _count = count;
}

-(int)count {
    return _count;
}

@end
           
//
//  main.m
//  04_Description
//
//  Created by apple on 14-11-9.
//  Copyright (c) 2014年 cc. All rights reserved.
//

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

int main(int argc, const char * argv[]) {
    
    @autoreleasepool {
        
        //通过构造给成员属性赋值赋值
        Goods* pGoods = [[Goods alloc] initWithAttribute:10 :20];
        
        NSLog(@"价格=%d, 数量=%d", pGoods.price, pGoods.count);
        
        
    }
    return 0;
}
           

通过控制台输出可以看到通过构造穿参也可以给成员属性赋值。

Objective-C 面向对象基础-构造方法