如何自动打印(使用NSLog)类的所有属性? [英] How to print (using NSLog) all properties of a class automatically?

查看:269
本文介绍了如何自动打印(使用NSLog)类的所有属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为在物业类型很复杂的情况下,打印出objective-c中任何类的所有属性的值是非常困难的。

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.

但是如果包含简单类型属性的类(如NSString,int,double,boolean),是否有任何方法可以自动NSLog而不是NSLog手动每个属性的值?

But if the class that contains properties with simple types (like, NSString, int, double, boolean), is there any way to NSLog automatically instead of NSLog manually the value of each property?

已更新

Updated:

您提供给我的所有解决方案仍然是手动的。有没有办法像遍历类的所有属性,NSLog variable_name variable_value 。这就是我的预期。

All the solutions you gave me are still manually. Is there any way like iterate through all properties of a class, and NSLog the variable_name and the variable_value. That's what I expected.

推荐答案

你可以通过覆盖 - (void)description 方法。

示例:
假设我们有简单的 Car 类。

@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

将此内容放入 NSDictionary 将在控制台中创建非常好的输出。

Putting this in NSDictionary will create very nice output in console.

另一方面,您可以在 NSObject class并执行以下操作:

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];
}

然后你将避免重写 - (void)description 类中的方法。

Then you will avoid overriding -(void)description method in your classes.

这里

这篇关于如何自动打印(使用NSLog)类的所有属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆