如何自动打印(使用NSLog)类的所有属性?
我认为在属性类型很复杂的情况下,打印出objective-c中任何类的所有属性的值是非常困难的。
但是如果包含具有简单类型属性的类(如NSString,int,double,boolean),是否有任何方法可以自动NSLog而不是NSLog手动获取每个属性的值?
更新 :
你给我的所有解决方案仍然是手动的。 是否有任何方法可以遍历类的所有属性,NSLog是variable_name和variable_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类的信息。
- 如何使用Document目录中的UIWebview打开和查看iphone中的.doc,.docx,.rtf,.ppt,.pptx,.xlsx,.xls文件?
- iOS clipsToBounds YES和Shadow?
- AVPlayer播放,暂停和缓冲问题
- 从UITabBarController初始化viewControllers
- (UIApplication.sharedApplication()。委托为AppDelegate).managedObjectContext
- 如何获得可拖延的MKAnnotationView没有任何延迟?
- Firebase – 检查高效的用户名
- 如何将iPhone连接到电视?
- TouchID调用applicationWillResignActive和applicationDidBecomeActive
- 我可以在不使用Xcode IDE的情况下构buildiOS的静态库吗?
- 我必须在第一个版本中启用版本控制才能在后续版本中使用轻量级迁移吗?