0C-013.OC中的description方法

时间:2021-09-08 14:56:30

description的翻译:描述

description这个方法是用来描述对象的。

NSObject这个基类已经包含了这个方法,重写的作用是输出自己想要的描述。

#import <Foundation/Foundation.h>//------main
#import "LSPerson.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
LSPerson *per = [[LSPerson alloc] init];
[per setAge:10];
// NSLog(@"%@",per); //打印<LSPerson: 0x100200980>
// NSLog(@"%p",per); //打印0x100200980
// 如果不重写对象上得description方法,它会找到父类的description方法,打印这个类的类名和它的地址
NSLog(@"%@",per);//如果重新description方法,打印 age = 10
Class className = [per class];//对象方法返回类
// NSLog(@"%@",className);//如果不重写类的description方法,输出类名
NSLog(@"%@",className);//打印 我变成了龙叔叔
NSLog(@"%@",[LSPerson class]);//类方法返回类
}
return 0;
}
#import <Foundation/Foundation.h>//------LSPerson.h@interface LSPerson : NSObject{    int _age;}- (void) setAge:(int) age;@end
#import "LSPerson.h"//------LSPerson.m@implementation LSPerson- (void) setAge:(int) age{    _age = age;}//如果需要输出自己想要的内容,需要重写这个对象方法-(NSString *)description{    return [NSString stringWithFormat:@"age = %d",_age];}+(NSString *)description{ //重写类中的description方法    return [NSString stringWithFormat:@"我变成了龙叔叔"];}@end