有没有办法记录Objective-C实例的所有属性值

dav*_*Mac 18 properties objective-c nslog

我只是想知道是否有一种快速简便的方法可以将所有属性的各种值打印到日志中以进行调试.就像我想知道所有BOOL,浮点数等的值是什么.

Tie*_*eme 27

这个问题似乎可以解答你的问题.

更新:

我好奇并做了一个类比:

//Using Xcode 4.5.2 - iOS 6 - LLDB - Automatic Reference Counting

//NSObject+logProperties.h    
@interface NSObject (logProperties)
- (void) logProperties;
@end

//NSObject+logProperties.m
#import "NSObject+logProperties.h"
#import <objc/runtime.h>

@implementation NSObject (logProperties)

- (void) logProperties {

    NSLog(@"----------------------------------------------- Properties for object %@", self);

    @autoreleasepool {
        unsigned int numberOfProperties = 0;
        objc_property_t *propertyArray = class_copyPropertyList([self class], &numberOfProperties);
        for (NSUInteger i = 0; i < numberOfProperties; i++) {
            objc_property_t property = propertyArray[i];
            NSString *name = [[NSString alloc] initWithUTF8String:property_getName(property)];
            NSLog(@"Property %@ Value: %@", name, [self valueForKey:name]);
        }
        free(propertyArray);
    }    
    NSLog(@"-----------------------------------------------");
}

@end
Run Code Online (Sandbox Code Playgroud)

将它包含在您的班级中: #import "NSObject+logProperties.h"

并致电[self logProperties];这些物业!


mat*_*way 6

目前的答案只是展示了如何为属性做到这一点.如果您希望打印出每个实例变量,您可以执行以下操作.

- (void)logAllProperties {
    unsigned int count;
    Ivar *ivars = class_copyIvarList([self class], &count);
    for (unsigned int i = 0; i < count; i++) {
        Ivar ivar = ivars[i];

        const char *name = ivar_getName(ivar);
        const char *type = ivar_getTypeEncoding(ivar);
        ptrdiff_t offset = ivar_getOffset(ivar);

        if (strncmp(type, "i", 1) == 0) {
            int intValue = *(int*)((uintptr_t)self + offset);
            NSLog(@"%s = %i", name, intValue);
        } else if (strncmp(type, "f", 1) == 0) {
            float floatValue = *(float*)((uintptr_t)self + offset);
            NSLog(@"%s = %f", name, floatValue);
        } else if (strncmp(type, "@", 1) == 0) {
            id value = object_getIvar(self, ivar);
            NSLog(@"%s = %@", name, value);
        }
        // And the rest for other type encodings
    }
    free(ivars);
}
Run Code Online (Sandbox Code Playgroud)

虽然我不特别建议在实践中这样做,但如果它是出于调试目的那么那就没问题.您可以将其作为一个类别实现,NSObject并保持它在调试时使用.如果完成所有类型编码,那么它可以成为一个非常好的小方法.


Gaé*_*anZ 6

现在有这些方法NSObject

@interface NSObject (Private)
-(id)_ivarDescription;
-(id)_shortMethodDescription;
-(id)_methodDescription;
@end
Run Code Online (Sandbox Code Playgroud)

迅速:

myObject.perform("_ivarDescription")
Run Code Online (Sandbox Code Playgroud)

感谢这篇文章