大白话解析Objective-C(三):构造方法+description方法

1、构造方法

//Book.h

#import <Foundation/Foundation.h>

@interface Book : NSObject {
    int _ID;
    double _price;
}

//set方法和get方法
- (void)setID:(int)ID;
- (int)ID;
- (void)setPrice:(double)price;
- (double)price;

//构造方法一般以init开头
- (id)initWithPrice:(double)price;
- (id)initWithID:(int)ID andPrice:(double)price;

@end

//Book.m

#import "Book.h"

@implementation Book

- (void)setID:(int)ID {
    _ID = ID;
}
- (int)ID {
    return _ID;
}
- (void)setPrice:(double)price {
    _price = price;
}
- (double)price {
    return _price;
}

- (id)initWithPrice:(double)price {
    //先调用父类的init方法,返回一个初始化对象赋值给self
    //再判断self是否为空,不为空才初始化_price
    if (self = [super init]) {
        //_price = price;
        self.price = price;   //也可以这样写(调用set方法)
    }
    return self;
}

- (id)initWithID:(int)ID andPrice:(double)price {
    if (self = [super init]) {
        self.ID = ID;
        self.price = price;
    }
    return self;
}

@end

//main.m

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

int main()
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    //例1:
    //调用构造方法initWithPrice
    Book *b = [[Book alloc] initWithPrice:32.55555555];
    //保留两位小数输出
    NSLog(@"price is %.2f", b.price);

    //例2:
    //构造的同时初始化多个变量
    Book *b2 = [[Book alloc] initWithID:1001 andPrice:105.12345];
    NSLog(@"id is %i, price is %.2f", b2.ID, b2.price);

    [b release];
    [b2 release];

    [pool drain];
    return 0;
}
运行结果:

2、description方法

//Book.h

#import <Foundation/Foundation.h>

@interface Book : NSObject {
    double _price;
}

//set方法和get方法
- (void)setPrice:(double)price;
- (double)price;

@end

//Book.m

#import "Book.h"

@implementation Book

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

@end

//main.m
#import <Foundation/Foundation.h>
#import "Book.h"

int main()
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    Book *b = [[Book alloc] init];

    //"%@"输出调用对象的description方法
    //这里没重写description方法,所以是默认输出类名和16进制地址
    NSLog(@"%@", b);

    [b release];

    [pool drain];
    return 0;
}

运行结果:


3、重写description方法

//Book.m

#import "Book.h"

@implementation Book

- (void)setPrice:(double)price {
    _price = price;
}
- (double)price {
    return _price;
}
//重写description方法
- (NSString *)description { //NSString 是OC对象的字符串,要加*号是因为OC的所有对象都是指针
    NSString *s = [NSString stringWithFormat:@"price is %.2f", _price];
    return s;
}

@end
运行结果:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值