What is the Objective-C equivalent for “toString()”, for use with NSLog?

吃可爱长大的小学妹 提交于 2019-11-26 19:02:54

问题


Is there a method that I can override in my custom classes so that when

      NSLog(@"%@", myObject) 

is called, it will print the fields (or whatever I deem important) of my object? I guess I'm looking for the Objective-C equivalent of Java's toString().


回答1:


It is the description instance method, declared as:

- (NSString *)description

Here's an example implementation (thanks to grahamparks):

- (NSString *)description {
   return [NSString stringWithFormat: @"Photo: Name=%@ Author=%@", name, author];
}



回答2:


Add this to the @implementation of your Photo class:

- (NSString *)description {
   return [NSString stringWithFormat:@"Photo: Name=%@ Author=%@",name,author];
}



回答3:


You can override the description method of NSObject:

- (NSString *)description

On the subject of logging I recommend this blog post for better logging in Objective-C.




回答4:


There are two functions that you can use.

- (NSString*)description

This will be displayed when you put your object as, I.E. a parameter for NSLog. The other description function is:

- (NSString*)debugDescription

This will be called when you do po anInstanceOfYourClass in the debug command window. If your class doesn't have a debugDescription function, then just description will be called.

Note that the base class NSObject does have description implemented, but it is fairly bare-bones: it only displays the address of the object. This is why I recommend that you implement description in any class you want to get info out of, especially if you use the description method in your code. If you do use description in your code, I suggest you implement debugDescription as well, also making debugDescription more verbose.




回答5:


This will output the available voices:

    NSLog((@"speechVoices:%", [[AVSpeechSynthesisVoice speechVoices] description] ));


来源:https://stackoverflow.com/questions/1104746/what-is-the-objective-c-equivalent-for-tostring-for-use-with-nslog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!