2011-01-31 217 views
1

我有一個NSMutableArray,我加載了不同的對象(類)。循環遍歷一個NSMutableArray

現在我需要通過數組並獲得進一步操作的類。

我嘗試這種方法...

for (id obj in allPointsArray) 
    { 
///// this is where i need to bring the obj into a class to work with 
    NSInteger loc_x = obj.x_coord; 
    NSInteger loc_y = obj.y_coord; 
    } 

,但我不能讓我的頭周圍竟使類從數組中,並把它變成一個usuable對象。

x_coord和y_coord在存儲在數組中的所有對象之間是通用的。

感謝大家幫助

+0

我想你可以得到類的類型,如果你使用[對象類]並將其與期望的類進行比較。但我不知道我是否正確地解決了問題...... – 2011-01-31 18:10:04

回答

5

如果數組中的對象具有不同的類,您是否嘗試做不同的事情?你可以這樣做:

for (id obj in myArray) { 
    // Generic things that you do to objects of *any* class go here. 

    if ([obj isKindOfClass:[NSString class]]) { 
     // NSString-specific code. 
    } else if ([obj isKindOfClass:[NSNumber class]]) { 
     // NSNumber-specific code. 
    } 
} 
3

如果使用消息語法,而不是點一個的代碼應工作:

for (id obj in allPointsArray) { 
    NSInteger loc_x = [obj x_coord]; 
    NSInteger loc_y = [obj y_coord]; 
} 

或者你可以寫你的所有點的共同協議:

@protocol Pointed 
@property(readonly) NSInteger x_coord; 
@property(readonly) NSInteger y_coord; 
@end 

@interface FooPoint <Pointed> 
@interface BarPoint <Pointed> 

現在,您可以縮小迭代類型並使用點語法:

for (id<Pointed> obj in allPointsArray) { 
    NSInteger loc_x = obj.x_coord; 
    NSInteger loc_y = obj.y_coord; 
} 

取決於上下文。

+1

`obj.x_coord`與* [[obj x_coord]] *是*相同的。他們編譯完全一樣的東西。 – 2011-01-31 18:10:45

+0

@Dave DeLong:他們編譯爲相同的東西*當且僅當*這兩個示例中的變量都具有相同的靜態類型,並且您使用默認的訪問者名稱。這裏變量沒有靜態類型,所以編譯器會拒絕點語法。 – Chuck 2011-01-31 18:15:16

0

您可以使用NSObject的-isKindOfClass:實例方法來檢查您的對象是否具有類成員資格。正是如此:

for (id obj in allPointsArray) { 
    if ([obj isKindOfClass:[OneThing class]]) { 
     OneThing* thisThing = (OneThing *)obj; 
     .... 
    } 
    else if ([obj isKindOfClass:[OtherThing class]]) { 
     OtherThing *thisThing = (OtherThing *)obj; 
     .... 
    } 
} 

如果你這樣做的,它不僅將編譯,但Xcode中會建議基於類有用的代碼補全你鑄造thisThing來。