Is there a way to log all the property values of an Objective-C instance

前端 未结 5 1708
庸人自扰
庸人自扰 2021-02-04 03:22

I was just wondering if there is a quick and easy way of printing out to the log all of the various values of the properties to my class for debugging purposes. Like I would lik

5条回答
  •  半阙折子戏
    2021-02-04 03:30

    The current answers just show how to do it for properties. If you want every instance variable printed out you could do something like the below.

    - (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);
    }
    

    Although I wouldn't particularly suggest doing this in practice, but if it's for debug purposes then that's fine. You could implement this as a category on NSObject and keep it lying around for use when debugging. If completed for all type encodings then it could make for a very nice little method.

提交回复
热议问题