-(NSString *) description


#1

This chapter has been quite challenging for me-lots of new things, and well, not enough explanation I suppose (but that might be on purpose).

I am baffled by

-(NSString*)description

method. When does this get called? I understand it is overriding the superclass, but I don’t understand how this, or -(void)dealloc ever get called.

What is ‘description’?? I’ve looked in apple documentation, but still am pretty lost.

Otherwise, I think I kind of understand things…hoping it might clear up as I go on with the challenges.

Thank you!


#2

They are normally called behind the scenes: dealloc by the runtime system and description by the NSLog function.

...
SomeClass *someObject = [SomeClass new];
...
NSLog (@"Some object: %@", someObject);

However, the description method can be called also directly.

//  main.m

#import <Foundation/Foundation.h>

// Every class is a subclass of NSObject class, either directly and indirectly.
@interface Foo : NSObject
@end

@interface FooBar : Foo
@end

@interface InvisibleFooBar : FooBar
@end

int main (int argc, const char * argv[])
{
    @autoreleasepool {
        
        // Let NSLog call the description method
        Foo *foo = [Foo new];
        NSLog (@"%s: %@", __func__, foo);
        
        FooBar *fooBar = [FooBar new];
        NSLog (@"%s: %@", __func__, fooBar);

        InvisibleFooBar *invFooBar = [InvisibleFooBar new];
        NSLog (@"%s: %@", __func__, invFooBar);
        
        // Call the description method directly
        FooBar *fooBar2 = [FooBar new];
        NSLog (@"%s: %@", __func__, [fooBar2 description]);
    }
    return 0;
}

@implementation Foo

// Use superclass's description

@end

@implementation FooBar

// Override
- (NSString *)description
{
    return [NSString stringWithFormat:@"I am a FooBar at %p", self];
}
@end

@implementation InvisibleFooBar

// Override
- (NSString *)description
{
    return @"";
}
@end

The description method is defined by the mother of all classes: NSObject. If a class does not override the description method, it will automatically inherit the one from it superclass.


#3

Thank you! Are there other functions that are called behind the scenes like description?

I can understand dealloc would be called by ARC when deallocation occurs, but what is the purpose of description?