If you’ve ever wondered if there’s a convenient way in Objective-C to write a function for “expressing” the value of an object of yours, as a string, just like “toString” in e.g. JavaScript (and Java? I think), I’ve got good news:
-(NSString *)description
Add the above method to your Objective-C class and you’ll be able to NSLog it or get its string value anywhere using [OBNAME description]. In short, it will now respond with its ‘description’ to ‘%@’ in an NSString stringWithFormat expression.
Example:
@interface Person : NSObject {
NSString *name;
NSString *phone;
NSInteger age;
}
-(NSString *)description;
[...]
-(NSString *)description
{
return [NSString stringWithFormat:@"%@ (%d): %@",
name, age, phone];
}
Then somewhere we have a Person object and we want to see its value.
NSLog(@"We've got %@", aPerson); myLabel.text = [NSString stringWithFormat:@"Details: %@", aPerson];
(pardon any errors in code above — untested as is)
Actually, ‘toString’ is the Java equivalent of the -description method. (Java was derived in part from Objecive-C.)
Huh! Didn’t know that! :O