2014-04-06 123 views
0

Here是如何枚舉JavaScript對象的屬性的一個示例。我注意到使用的循環結構是一個for...in循環。 Objective-C也有一個for...in循環,所以在Objective-C中可能有相同的行爲嗎?枚舉通過對象屬性

@interface Bar : NSObject 
@property (nonatomic) NSString * stringA; 
@property (nonatomic) NSString * stringB; 
@property (nonatomic) NSString * stringC; 
@end 

int main(int argc, const char *argv[]) { 
    Bar obj = [[Bar alloc] init]; 
    obj.stringA = @"1"; 
    obj.stringB = @"2"; 
    obj.stringC = @"3"; 

    for (NSString *property in obj) { 
     NSLog(@"%@", property); 
    } 
} 

Objective-C可能嗎?如果沒有,是否有一種替代方法會模仿迭代對象屬性的這種行爲?

+1

可能重複:// stackoverflow.com/questions/13881353/how-do-i-print-the-values-of-all-declared-properties-of-an-nsobject) –

+0

@EthanHolshouser看着它,像我一樣,它詢問有關看到所有一個對象的屬性,但我想看看是否有可能通過它們快速枚舉。 –

回答

2

Fast enumeration

Bar *obj = [[Bar alloc] init]; 
// ... 
for (id elem in obj) { 
    ... 
} 

要求類Bar符合NSFastEnumeration Protocol,即,它必須實現

countByEnumeratingWithState:objects:count: 

方法。 (這是所有Objective-C的集合類如NSArrayNSDictionaryNSSet的情況。)

那麼直接回答你的問題是沒有,您不能使用快速列舉語法for (... in ...)列舉的所有屬性一個任意的類。

但是,可以爲自定義類實現快速枚舉協議。 例子如何做到這一點可以在這裏找到

的[我如何打印一個NSObject的所有聲明的屬性的值是多少?(HTTP
2

簡短回答:是的,這是可能的

下面是您試圖實現的一些示例代碼。

@interface Bar : NSObject 

@property (nonatomic, retain) NSString *stringA; 
@property (nonatomic, retain) NSString *stringB; 
@property (nonatomic, retain) NSString *stringC; 

@end 

主要

@implementation Bar 
// don't forget to synthesize 
@synthesize stringA, stringB, stringC; 
@end 

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

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

讓我知道如果您有任何問題。