String toString() {
return "some string";
}
In Objective-C there is a similar class method on NSObject called description.
From the documentation description: "returns a string that describes the contents of the receiver."
WARNING: just because NSObject defines description does not mean the runtime will automatically recognize your override of the method UNLESS you explicitly declare it in your header (.h) file.
The header (.h) file
@interface MyObj : NSObject {
// instance variables
}
-(NSString *) description;
@end
Now the implementation (.m) file:
@implementation MyObj {
// instance variables
}
-(NSString *) description {
@interface MyObj : NSObject {
// instance variables
}
-(NSString *) description;
@end
Now the implementation (.m) file:
@implementation MyObj {
// instance variables
}
-(NSString *) description {
return @"My special override of description";
}
@end
@end
Now you can do something like the following:
...
MyObj mo = [[MyObj alloc] init];
NSLog( @"Your object is: %@", mo );
...
Output:
Your object is: My special override of description
No comments:
Post a Comment