在运行时循环遍历所有对象属性

Old*_*her 9 iphone cocoa-touch objective-c ios

我想创建一个Objective-C基类,它在运行时对所有属性(不同类型)执行操作.由于不会总是知道属性的名称和类型,我该怎么做这样的事情呢?

@implementation SomeBaseClass

- (NSString *)checkAllProperties
{
    for (property in properties) {
        // Perform a check on the property
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:这在自定义- (NSString *)description:覆盖中特别有用.

And*_*sen 22

为了扩展mvds的答案(在我看到他之前开始写这个),这里有一个小示例程序,它使用Objective-C运行时API循环并打印有关类中每个属性的信息:

#import <Foundation/Foundation.h>
#import <objc/runtime.h>

@interface TestClass : NSObject

@property (nonatomic, retain) NSString *firstName;
@property (nonatomic, retain) NSString *lastName;
@property (nonatomic) NSInteger *age;

@end

@implementation TestClass

@synthesize firstName;
@synthesize lastName;
@synthesize age;

@end

int main(int argc, char *argv[]) {
    @autoreleasepool {
        unsigned int numberOfProperties = 0;
        objc_property_t *propertyArray = class_copyPropertyList([TestClass class], &numberOfProperties);

        for (NSUInteger i = 0; i < numberOfProperties; i++)
        {
            objc_property_t property = propertyArray[i];
            NSString *name = [[NSString alloc] initWithUTF8String:property_getName(property)];
            NSString *attributesString = [[NSString alloc] initWithUTF8String:property_getAttributes(property)];
            NSLog(@"Property %@ attributes: %@", name, attributesString);
        }
        free(propertyArray);
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

房产年龄属性:T ^ Q,Vage
物业的lastName属性:T @家"的NSString",&,N,VlastName
物业的firstName属性:T @家"的NSString",&,N,VfirstName

请注意,此程序需要在启用ARC的情况下编译.


mvd*_*vds 15

使用

objc_property_t * class_copyPropertyList(Class cls, unsigned int *outCount)
Run Code Online (Sandbox Code Playgroud)

并阅读https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html,了解如何完全执行此操作.

一些代码可以帮助您:

#import <objc/runtime.h>

unsigned int count=0;
objc_property_t *props = class_copyPropertyList([self class],&count);
for ( int i=0;i<count;i++ )
{
    const char *name = property_getName(props[i]); 
    NSLog(@"property %d: %s",i,name);
}
Run Code Online (Sandbox Code Playgroud)