Default String representation of an NSObject

In Actionscript, if you subclass Object, and you want a default string representation of your subclass, you just implement the method ‘toString’. For example the following:

package {
	public class Thing { 
		public var name:String;
		public function toString() : String {
			return (“Thing: “+this.name);
		}
	}
}
...
var thing:Thing = new Thing();
thing.name = “thing”
trace(thing);  //trace: Thing: thing

In Objective C, it’s very similar, however instead of ‘toString’ you use ‘description’.

#import <Foundation/Foundation.h>

@interface Thing : NSObject
@property (strong,nonatomic) NSString *name;
@end

@implementation Thing
- (NSString *)description {
    return [NSString stringWithFormat: @"Thing: %@", self.name];
}
@end

...

Thing *thing = [[Thing alloc] init];
thing.name = @"thing"
NSLog(@"Thing: %@",thing);//log: Thing: thing

Interactive developer, Author - iOS development with Swift - book coming 2017 https://manning.com/books/ios-development-with-swift

Tagged with: ,
Posted in Objective C

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: