1.description方法是NSObject自帶的方法,包括類方法和對象方法
+ (NSString *)description; // 默認(rèn)返回 類名- (NSString *)description; // 默認(rèn)返回 <類名:內(nèi)存地址>
2.默認(rèn)情況下利用NSLog和%@輸出對象的時返回的就是類名和內(nèi)存地址
3.修改NSLog和%@的默認(rèn)輸出:重寫類對象或者實例對象的description方法即可。因為NSLog函數(shù)進(jìn)行打印的時候會自動調(diào)用description方法
/******************************** Person.h文件*********************************/#import <Foundation/Foundation.h>@interface Person : NSObject+ (NSString *)description;- (NSString *)description;@PRoperty int age;@property NSString *name;@end/******************************** Person.m文件*********************************/#import "Person.h"@implementation Person#pragma mark 類對象輸出的結(jié)果+ (NSString *)description{ return @"AAA";}#pragma mark 實例對象輸出的結(jié)果- (NSString *)description{ // NSLog(@"%@",self); 引發(fā)死循環(huán) return [NSString stringWithFormat:@"name = %@ age = %d",_name,_age];}@end/******************************** main.m文件***********************************/#import <Foundation/Foundation.h>#import "Person.h"int main(int argc, const char * argv[]){ Class c = [Person class]; NSLog(@"%@",c); Person *person = [[Person alloc] init]; person.name = @"John"; person.age = 20; // 執(zhí)行NSLog函數(shù)的時候會調(diào)用description方法默認(rèn)返回<類名/對象名: 地址> NSLog(@"%@",person); }
/**************************** 豐富日志輸出 **********************************/#import <Foundation/Foundation.h>#import "Person.h"int main(int argc, const char * argv[]){ Person *person = [[Person alloc] init]; // 打印person對象地址 NSLog(@"%@",person); // <Person: 0x100200ae0> // 打印person指針的地址 NSLog(@"%p",person); // 0x100200ae0 對象和指針地址一致 // 指針變量的地址 NSLog(@"%p",&person);// 0x7fff5fbff8e8 // NSLog不能%s無法輸出帶有中文的文件路徑,可以用c語言中的printf和%s來代替 // NSLog(@"%s",__FILE__); printf("%s",__FILE__); // 輸出當(dāng)前方法 NSLog(@"%s",__FUNCTION__); // 返回 main }
新聞熱點(diǎn)
疑難解答