NSLog an object's memory address in overridden description method

Objective CNslog

Objective C Problem Overview


I am overriding an object's description method. I need to know how to print the object's memory address to replace {???} in the code below:

-(NSString *) description {
    return [NSString stringWithFormat:@"<SomeClass: %@>\nparmeterOne: %@\nparameterTwo: %@",
            {???}, self.parameterOne, self.paramterTwo];
}

I want it to print in the console like this:

<SomeClass: 0x4c05600> parameterOne: 12 parameterTwo: sausages

Objective C Solutions


Solution 1 - Objective C

To print address use %p format specifier and self pointer:

-(NSString *) description {
    return [NSString stringWithFormat:@"<SomeClass: %p>\nparmeterOne: %@\nparameterTwo: %@",
            self, self.parameterOne, self.paramterTwo];
}

Solution 2 - Objective C

The easiest method is to use the super description
- (NSString *)description
{
    return [NSString stringWithFormat:@"%@ Area: %@, %@", [super description], self.identifier, self.name];
}

So in the case of this model object that is a subclass of NSObject, you can dodge extra work and remembering %p.

Manually using NSStringWithClass() and %p
- (NSString *)description
{
    return [NSString stringWithFormat:@"<%@: %p> Area: %@, %@", NSStringFromClass([self class]), self, self.identifier, self.name];
}

So in the case of an object model in which you have a concrete implementer that is derived from this class you will show the correct class name.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionUndistractionView Question on Stackoverflow
Solution 1 - Objective CVladimirView Answer on Stackoverflow
Solution 2 - Objective CCameron Lowell PalmerView Answer on Stackoverflow