Search code examples
objective-cnslognsobject

How to override the description method for an object and print it out?


I need to override the description method to return the internal state of the object (in other words, dump all the values into a single line of text).

In my Model(Class) I have

Homework.h

#import <Foundation/Foundation.h>

@interface Homework : NSObject

@property (nonatomic, strong) NSString *className;
@property (nonatomic, strong) NSString *assignmentTitle;

@end

Homework.m

-(NSString *)description
{
return [NSString stringWithFormat:@" %@, %@", self.className, self.assignmentTitle];
}

I created an object in my ViewController

@property (nonatomic, strong) Homework *homeworkAssignment;

And I try to print it like this

  NSLog(self.homeworkAssignment.description);

But it doesn't seem to work, the output prints out a comma ",". Am I formatting the NSLog wrong? Did I override the method correctly? This is my first app (besides "Hello World").


Solution

  • The code all appears correct with regard to the implementation of description and the logging. Since the output only shows a comma it means that your two property both contain empty strings. If they were nil the string format would display them as (null).

    There is a difference between a nil pointer and a reference to the empty string (@"").