If you have ever coded Java, you know how important the toString() method is. Well, objective-c has a similar method called Description. What overriding the description will allow you to do is, customize the output when you want to print your object.
Let’s take an example where you might have a class called User that contains a few properties.
@interface User : NSObject { NSInteger userID; NSString *name; NSString *website; } @end
Now, at this point if we did
NSLog(@"%@",user);
we would end up with output like
User: 0xd18f50
which is not very helpful. What would be better is when we want to print the user for it to display their userID, name, and website. This can be done by overriding the description method like this.
-(NSString *) description { return [NSString stringWithFormat:@"ID: %d\nName: %@\nWebsite: %@\n", userID,name,website]; }
Now when we call
NSLog(@"%@",user);
is will nicely display this:
ID: 42 Name: brandontreb Website: http://brandontreb.com
Note: NSLog is your best friend when debugging any objective-c application. Use it often. Also, to open up the Debugger Console, click Run -> Console.
Tags: debugger console, java tostring, objective-c programming, objectivec tostring
great tutorial thanks!
thanks a lot.to the point.
Thanks alot!!!