A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 洪吉童 中级黑马   /  2015-10-24 12:06  /  705 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

1、description方法概述

先看一个例子。我们定义一个Dog类:
创建类Dog:

  1. #import<Foundation/Foundation.h>
  2. @intface Dog : NSObject
  3. {
  4. @public
  5. int _tuiNum;  //定义变量腿的个数
  6. int _eyeNum;  //定义变量眼睛个数
  7. }
  8. -(void)run;        
  9. +(void)eat;
  10. @end
复制代码


实现这个类:
  1. @implementation Dog
  2. -(void)test{
  3. NSLog(@"对象方法");

  4. }
  5. +(void)test{
  6. NSLog(@"类方法");

  7. }
复制代码



main函数中:
  1. #import<Foundation/Foundation.h>
  2. #import"Dog.h"
  3. int main(int atgc,const char *argc[]){
  4. @autoreleasepool{
  5. Dog *d=[Dog new];   //创建一个对象d
  6. NSLog(@"%@",d);     //打印这个对象地址
  7. }
  8. return 0;
  9. }
复制代码



打印结果为:<Dog:0x100202280>
descriptong方法默认返回对象的描述信息(默认实现是返回类名和对象的内存地址)NSLog(@"%@", objectA);这会自动调用objectA的descriptong方法来输出ObjectA的描述信息,description方法是基类NSObject所带的方法,因为其默认实现是返回类名和对象的内存地址,这样的话,使用NSLog输出OC对象,意义就不是很大,因为我们并不关心对象的内存地址,比较关心的是对象内部的一些成变量的值。因此,会经常重写description方法,覆盖description方法的默认实现。

2、description重写的方法

1)对象的description方法

在Dog.m中我们重写入:

  1. @implementation Dog
  2. -(void)test{
  3. NSLog(@"对象方法");

  4. }
  5. +(void)test{
  6. NSLog(@"类方法");

  7. }
  8. -(NSString*)description{
  9. return [NSString stringWithFormat:@"狗腿的个数:%d,狗的眼睛个数:%d",_tuiNum,_eyeNum];
  10. }
复制代码


OK,现在再运行一下main函数:
  1. #import<Foundation/Foundation.h>
  2. #import"Dog.h"
  3. int main(int atgc,const char *argc[]){
  4. @autoreleasepool{
  5. Dog *d=[Dog new];
  6. d->_tuiNum=4;  //给变量赋值
  7. d->_eyeNum=2;  //给变量赋值
  8. NSLog(@"%@",d); //调用对象description方法
  9. }
  10. return 0;
  11. }
复制代码



打印出结果:狗腿的个数:4,狗的眼睛个数:2

2)类的description方法

类的description方法的重写入跟对象的重写入一样,只需要将-(void)变为+(void)即可。

  1. +(NSString*)description{
  2. return @"+开头的方法";     //注意类方法不能调用实例变量
  3. }
复制代码


main的实现
  1. int main(int atgc,const char *argc[]){
  2. @autoreleasepool{
  3. Dog *d=[Dog new];
  4. NSLog(@"%@",[d class]);  //[d class]为通过对象名获取类对象,或者使用[Dog class]
  5. }
  6. return 0;
  7. }
复制代码


3、description陷阱

千万不要在对象description方法中同时使用%@和self,下面的写法是错误的:

  1. - (NSString *)description {
  2.     return [NSString stringWithFormat:@"%@", self];
  3. }
复制代码


同时使用了%@和self,代表要调用self的description方法,因此最终会导致程序陷入死循环,循环调用description方法。


0 个回复

您需要登录后才可以回帖 登录 | 加入黑马