C++中可以直接打印对象指针,打印的就是该指针指向的虚拟内存地址,Java中通过打印对象可以输出对象的虚拟内存地址,OC中同样可以通过打印对象指针来输出对象的虚拟内存地址,也提供了description方法来控制打印的内容,子类重写父类的description方法即可实现任意的打印效果,用法同Java中重写toString()方法几乎完全一样。
//
// 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;
- (NSString *)description;
@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;
}
/**
* description方法相当于Java中的toString()方法,默认是打印对象的地址,可以自己重写来实现打印对象的属性
*
* @return 字符串
*/
- (NSString *)description {
//stringWithFormat 格式化字符串函数
return [NSString stringWithFormat:@"price=%d, count=%d", _price, _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];
//通过%@格式占位符,默认是打印对象的地址
//通过重写父类的description方法来实现打印其对象的成员属性
//用法和Java中的toString()有异曲同工之妙
NSLog(@"%@", pGoods);
}
return 0;
}