How can I see values of Object in NSLog?
Implement description
of the given class.
-(NSString*)description {
return [NSString
stringWithFormat:@"<%@> name: `%@` size: `%@`",
NSStringFromClass(self), self.name,
NSStringFromCGSize(self.size)];
}
NSLog(@"%@", object); // <Object> name: `Harry` size: `{2, 2}`
extension Object: CustomStringConvertible {
var description: String {
"<\(Self.self)> name: `\(name)` size: `\(size)`"
}
}
print(object) // <Object> name: `Harry` size: `(2.0, 2.0)`
If you implement the -(NSString*)description
method in your class then you can use NSLog
to output a summary of the data. Of course, you can also directly output any property.
For example:
NSLog (@"%@ %d", object, object.integer);
The first part calls the description
method and outputs that; the second part gets the value of the integer property of object and outputs that.
If you want to see an NSArray and NSDictionary and etc objects then you can directly print like NSLog(@"%@",object);
If it is an user defined object then you need to display by calling with property (attribute).
User defined object with name object and properties like
NSString *property1;
int property2;
NSMutableArray *property3;
Print them in the console as follows:
NSLog(@"%@, %d, %@" object.property1,object.property2,object.property3);
Every Objective-c Object (this comes from NSObject) has a property called description
. So if you want to print information about your class this is the way to go.
@implementation MyClass
- (NSString*)description
{
return [NSString stringWithFormat:@"MyClass:%@", @"This is my class"];
}
so if you do a call like this.
MyClass *myClass = [[MyClass alloc] init];
NSLog(@"%@", myClass);
NSLog(@"%@", [myClass description]); //Same as the line above
Then it will write "MyClass:This is my class"
to the console (in this case it will print it twice).