是什么?
是NSObject中定义的描述方法.
+(void)description:类方法
-(void)description;对象方法
有什么用?
返回类对象或实例对象的描述!
怎么用?
[类名 description] //默认,打印类名
[对象名 decription]//默认,打印<类名 类的对象的地址(16进制数)>
NSLog("类 = @% --- 对象 =@%",类名,对象名):
什么时候用?
场景:调试代码时,可以直接打印出属性的值!
用的时候需要注意什么?
1)类方法里面不能调用属性
2)自定义的方法,要声明!重写的方法不需要声明!
3)stringWithFormat:@"字符串格式",参数格式化字符串方法.(已现有的格式,输出字符串) 有什么优势和劣势?
优势:调试的时候可以打印出属性的值,查错方便!(不需要设断点)
劣势: 要写代码! - //
- // Person.h
- //
- #import <Foundation/Foundation.h>
- @interface Person : NSObject
- @property NSString * name;
- @property int age;
- //自定义构造方法
- -(id)initPerName:(NSString *)name Age:(int)age;
- @end
- //
- // Person.m
- //
- #import "Person.h"
- @implementation Person
- //自定义构造方法
- -(id)initPerName:(NSString *)name Age:(int)age{
- if(self = [super init]){
- _name = name;
- _age = age;
- }
- return self;
- }
- //子类重写父类的方法
- -(NSString *)description
- {
- return [NSString stringWithFormat:@"(对象方法)名称:%@,(对象方法)年龄:%d",_name,_age];
- }
- //问题:下面错在哪里?
- //类方法里面不能调用属性!
- //+(NSString *)description
- //{
- // return [NSString stringWithFormat:@"(类方法)名称:%@,(类方法)年龄:%d",_name,_age];
- //}
- //重写父类的类方法
- +(NSString *)description
- {
- return @"(类方法)hahaha...";
- }
- @end
- /*
- main.m
-
- description 描述
- 是什么?
- 是NSObject里面定义的方法
- +(void)description{}
- -(void)description{}
- 做什么用?
- 返回实例对象或类对象的描述!
- 什么时候用?
- 场景:调试的时候,想要知道当前类/对象的属性的值?
-
- */
- #import <Foundation/Foundation.h>
- #import "Person.h"
- int main(int argc, const char * argv[]) {
- Person *per =[[Person alloc]init];
- Class cper = [Person class];
- NSLog(@"实例化对象的描述%@,类对象的描述%@",[per description],[cper description]);
-
-
- Person *per2 =[[Person alloc]initPerName:@"huh.." Age:34];
- // per2.age =10;
- // per2.name=@"hun";
-
- NSLog(@"对象方法的描述%@,类方法的描述%@",[per2 description],[Person description] );
-
- return 0;
- }
复制代码
|