要在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編譯打開。
一個好的後續問題將是如何返回每個動態值...我想動態地創建一個訪問器,但在語法上,我仍然試圖找出。 – 2012-02-14 00:07:58
有幾種方法可以做到這一點,但最直接的方法是使用KVC:'id value = [self valueForKey:@「propertyName」]''。在你有原始(int,float等)和對象(NSString等)返回類型的地方獲得更復雜一點,但基本前提將起作用。 – 2012-02-14 00:37:45
這段代碼像地獄一樣泄漏 – mvds 2012-02-14 00:53:01