开发者

Looping through an NSMutableArray

I have a NSMutableArray that I load up with different objects (classes).

Now I need to go through the array and get to the classes for further manipulation.

I was trying this approach...

for (id obj in allPointsArray)   
  {
///// 开发者_Go百科  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;
  }

but I cannot get my head around actually bringing the class out of the array and placing it into a usuable object.

the x_coord and y_coord are common between all of the objects stored in the array.

Thanks for everyone help


Are you trying to do different things if the objects in the array are of different classes? You could do something like this:

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.
    }
}


The code should work if you use the message syntax instead of the dot one:

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

Or you could write a common protocol for all your points:

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

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

Now you could narrow the type in the iteration and use the dot syntax:

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

Depends on the context.


You can use the -isKindOfClass: instance method of NSObject to inspect your objects for class membership. Thusly:

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

If you do it that way, not only will it compile, but Xcode will suggest helpful code completions based on the class you're casting thisThing to.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜