2012-02-13 4 views
9

런타임에 다양한 유형의 모든 속성에 대해 작업을 수행하는 Objective-C 기본 클래스를 만들고 싶습니다. 속성의 이름과 유형을 항상 알 수는 없으므로 어떻게해야합니까?런타임시 모든 객체 속성을 반복합니다.

@implementation SomeBaseClass 

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

편집 :이 사용자 정의 - (NSString *)description: 재정에 특히 유용 할 것이다.

답변

21

이 MVDS '답변을 확장하려면 여기를 통해 루프에 목표 - 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 012 3, 속성이 lastName 속성 : T의 @ "는 NSString", &, N, VlastName
속성 인 firstName 속성 : T의 @ "는 NSString", &, N, VfirstName

주이 프로그램은 ARC 컴파일 할 필요가 있음 켜져있다.

+0

좋은 후속 질문은 각각의 동적 값을 반환하는 방법이 될 것입니다 ... 나는 접근자를 동적으로 생성한다고 생각하지만 구문 론적으로, 나는 여전히 그것을 파악하려고합니다. –

+1

당신이 할 수있는 몇 가지 방법이 있지만, 가장 간단한 것은 KVC를 사용하는 것입니다 :'id value = [self valueForKey : @ "propertyName"]'. 기본 (int, float 등) 및 객체 (NSString 등) 반환 유형을 모두 가지고있는 경우 좀 더 복잡해 지지만 기본적인 전제가 작동합니다. –

+0

이 코드는 지옥 같아요. – mvds

14

사용

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

하고 정확하게이 작업을 수행하는 방법에 대한 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); 
} 
+1

스텔라. 더 가까운 금속 실행 시간 광기를위한 완벽한 자원. –

+0

고마워요, 잘 작동합니까, 런타임에 한 객체 속성을 다른 객체에 어떻게 복사합니까? –

+1

@PavanSaberjack'valueForKey :'와'setValue : forKey :'를 사용하여 어떤 형태의 변환없이'char * name'을 객체 (즉, NSString)로 사용할 수 없음을 알아야합니다. – mvds

관련 문제