如何自动打印(使用NSLog)类的所有属性?

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

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

更新

你给我的所有解决方案仍然是手动的。 是否有任何方法可以遍历类的所有属性,NSLog是variable_namevariable_value 。 这就是我的预期。

您可以通过覆盖-(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中将在控制台中创建非常好的输出。

另一方面,您可以在NSObject类上创建类别并执行以下操作:

 - (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方法。

从这里获取它

使用NSObject子类在Objective-C中实现您正在寻找的最优雅的方法,它覆盖NSObject方法description

例如(假设您的Class有一个名为propertyX的属性):

 -(NSString *)description { return [NSString stringWithFormat:@"", [self objectID], [self propertyX].x, [self propertyX].y]; } 

NSObject的默认description实现将只返回指向该对象的内存地址,如下所示:

 NSLog(@"%@", self); 

2015-06-15 14:20:30.123 AppName […] myCustomObject:0x000000>

但是,通过覆盖如上所示的此基类方法,您将能够自定义此行为,并且日志将如下所示:

2015-06-15 14:20:30.123 AppName […] myCustomObject:0x000000 someProperty,Property:blah,blah>

有一个很好的教程,在这里进一步讨论。

示例: –

  + (NSString *)description; [NSString description]; 

为您提供有关NSString类的信息。