I think it\'s very difficult to print out the value of all properties of any class in objective-c, in the case the type of the property is complex.
But if the class that
You can do this by overriding -(void)description
method.
Example:
Let's say we have simple Car
class.
@interface Car : NSObject
@property (copy, nonatomic) NSString *model;
@property (copy, nonatomic) NSString *make;
@property (strong, nonatomic) NSDate *registrationDate;
@property (assign, nonatomic) NSInteger mileage;
@property (assign, nonatomic) double fuelConsumption;
@end
@implementation
- (NSString*)description {
return [NSString stringWithFormat:@"<%@:%p %@>",
[self className],
self,
@{ @"model" : self.model,
@"make" : self.make,
@"registrationDate": self.registrationDate,
@"mileage" : @(self.mileage),
@"fuelConsumption" : @(self.fuelConsumption)
}];
}
@end
Putting this in NSDictionary
will create very nice output in console.
On the other hand, you can create category on NSObject
class and do something like this:
- (NSString*)myDescriptionMethod {
NSMutableDictionary *dict = [NSMutableDictionary new];
unsigned int count;
objc_property_t *properties = class_copyPropertyList([self class], &count);
for (int i = 0; i < count; i++) {
const char *property = property_getName(properties[i]);
NSString *propertyString = [NSString stringWithCString:property encoding:[NSString defaultCStringEncoding]];
id obj = [self valueForKey:propertyString];
[dict setValue:obj forKey:propertyString];
}
free(properties);
return [NSString stringWithFormat:@"<%@ %p %@>",
[self class],
self,
dict];
}
Then you will avoid overriding -(void)description
method in your classes.
Get it from here
The most elegant way to achieve what you're looking for in Objective-C with NSObject
subclasses, it to override the NSObject
method description
.
For example (assuming your Class has a property called propertyX):
-(NSString *)description
{
return [NSString stringWithFormat:@"<myCustomObject: %@, propertyX: %f, %f>",
[self objectID], [self propertyX].x, [self propertyX].y];
}
The default description
implementation of NSObject
will simply return the memory address pointed to for the object, like so:
NSLog(@"%@", self);
2015-06-15 14:20:30.123 AppName[...] myCustomObject: 0x000000>
However, by overriding this base Class method as shown above, you will be able to customise this behavior, and the log will look like this:
2015-06-15 14:20:30.123 AppName[...] myCustomObject: 0x000000 someProperty, Property: blah, blah>
There is a nice tutorial, which discusses this further here.
Example :-
+ (NSString *)description;
[NSString description];
Gives you information about the class NSString.