天天看點

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 面向對象基礎-構造方法