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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© huh 中级黑马   /  2015-12-25 23:52  /  513 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

是什么?
    是NSObject中定义的描述方法.
    +(void)description:类方法
    -(void)description;对象方法

有什么用?
    返回类对象或实例对象的描述!
怎么用?
    [类名 description] //默认,打印类名
    [对象名 decription]//默认,打印<类名 类的对象的地址(16进制数)>
    NSLog("类 = @% --- 对象 =@%",类名,对象名):
什么时候用?
    场景:调试代码时,可以直接打印出属性的值!
用的时候需要注意什么?
    1)类方法里面不能调用属性
    2)自定义的方法,要声明!重写的方法不需要声明!
    3)stringWithFormat:@"字符串格式",参数格式化字符串方法.(已现有的格式,输出字符串)

有什么优势和劣势?
    优势:调试的时候可以打印出属性的值,查错方便!(不需要设断点)
    劣势: 要写代码!

  1. //
  2. //  Person.h
  3. //
  4. #import <Foundation/Foundation.h>
  5. @interface Person : NSObject
  6. @property NSString * name;
  7. @property int age;
  8. //自定义构造方法
  9. -(id)initPerName:(NSString *)name Age:(int)age;
  10. @end
  11. //
  12. //  Person.m
  13. //
  14. #import "Person.h"
  15. @implementation Person
  16. //自定义构造方法
  17. -(id)initPerName:(NSString *)name Age:(int)age{
  18.     if(self = [super init]){
  19.         _name = name;
  20.         _age = age;
  21.     }
  22.     return self;
  23. }
  24. //子类重写父类的方法
  25. -(NSString *)description
  26. {
  27. return [NSString stringWithFormat:@"(对象方法)名称:%@,(对象方法)年龄:%d",_name,_age];
  28. }
  29. //问题:下面错在哪里?
  30. //类方法里面不能调用属性!
  31. //+(NSString *)description
  32. //{
  33. //    return [NSString stringWithFormat:@"(类方法)名称:%@,(类方法)年龄:%d",_name,_age];
  34. //}
  35. //重写父类的类方法
  36. +(NSString *)description
  37. {
  38.     return @"(类方法)hahaha...";
  39. }
  40. @end
  41. /*
  42. main.m

  43. description 描述
  44. 是什么?
  45.     是NSObject里面定义的方法
  46.     +(void)description{}
  47.     -(void)description{}
  48. 做什么用?
  49.     返回实例对象或类对象的描述!
  50. 什么时候用?
  51.     场景:调试的时候,想要知道当前类/对象的属性的值?
  52.    
  53. */
  54. #import <Foundation/Foundation.h>
  55. #import "Person.h"
  56. int main(int argc, const char * argv[]) {
  57.     Person *per =[[Person alloc]init];
  58.     Class cper = [Person class];
  59.     NSLog(@"实例化对象的描述%@,类对象的描述%@",[per description],[cper description]);
  60.    
  61.    
  62.     Person *per2 =[[Person alloc]initPerName:@"huh.." Age:34];
  63.     //    per2.age =10;
  64.     //    per2.name=@"hun";
  65.    
  66.     NSLog(@"对象方法的描述%@,类方法的描述%@",[per2 description],[Person description] );
  67.    
  68.     return 0;
  69. }
复制代码


0 个回复

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