IOS重寫description方法,自訂控制台(log)資訊

來源:互聯網
上載者:User

標籤:des   style   blog   io   color   os   sp   for   strong   

description是所有類都有的一個方法。

我們重寫這個方法,可以自訂執行個體輸出的資訊。

 

比如我們建立一個Person類:

在.h檔案中添加兩個屬性:

#import <Foundation/Foundation.h>@interface Person : NSObject@property (strong, nonatomic) NSString *name;@property (assign, nonatomic) int age;@end

在.m檔案中重寫description方法:

#import "Person.h"@implementation Person- (NSString *)description{    return [NSString stringWithFormat:@"<%p> - name: %@, age: %d", self, _name, _age];}@end

 

我們調用一下:

Person *person = [[Person alloc] init];person.name = @"XiaoMing";person.age = 28;NSLog(@"person - %@", person);

 

 這時控制台會輸出:

person - <0x7fa20bc18d10> - name: XiaoMing, age: 28

這個是我description中自訂的輸出方法。

 

如果我們沒有重寫description方法,控制台輸出的結果則為:

person - <Person: 0x7fccd1e1c5f0>

 

總結一下:

也就是說當我們把該類的所有屬性都輸出至控制台時,我們可以重寫description方法,方便我們能隨時觀察類的各個屬性。

PS: 沒有重寫description方法時,預設只會顯示列印的類名和類的記憶體位址。

IOS重寫description方法,自訂控制台(log)資訊

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.