Craig Grummitt – Before I forget

Discoveries in Swift and iOS development.

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:

[sourcecode language=”actionscript3″]
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

[/sourcecode]

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

[sourcecode language=”objc”]
#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
[/sourcecode]


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *