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

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

@implementation SomeBaseClass - (NSString *)checkAllProperties { for (property in properties) { // Perform a check on the property } } 

编辑:这将是特别有用的自定义- (NSString *)description:覆盖。

为了扩展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); } } 

输出:

物业时代属性:T ^ q,Vage
属性lastName属性:T @“NSString”,&,N,VlastName
属性firstName属性:T @“NSString”,&,N,VfirstName

请注意,这个程序需要在ARC打开的情况下编译。

使用

 objc_property_t * class_copyPropertyList(Class cls, unsigned int *outCount) 

并阅读https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html关于如何做到这一点&#x3002;

一些代码让你去:

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