How to print (using NSLog) all properties of a class automatically?

后端 未结 3 1887
滥情空心
滥情空心 2021-01-28 09:11

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

3条回答
  •  心在旅途
    2021-01-28 09:29

    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

提交回复
热议问题