开发者

How to determine the type of items in an NSSet

For example, the method:

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event

in UIResponder has an NSSet* touches as the parameter.

In the method itself, how do I determine what type of object touches开发者_Go百科 actually contain? In this case, it contains a set of UITouch. But I knew that from reading some tutorials online.

In general, how do I know what kind of object the set contains?


As Aran said, you can use isKindOfClass: to determine the type of the items in an NSSet. Or you can ask any given item for its -class and go that route.

But don't.

Throughout Cocoa, it is exceedingly rare to see code that changes behavior based upon the class of an item where the class is not determined as part of the software design process.

Thus, whenever code is using isKindOfClass: to handle various items in a collection, it is almost always an indication of an architectural issue -- almost always an indication that the code is using patterns that are either sub-optimal or otherwise alien to Cocoa.


you can ask an object in the set if it is a particular type

if ([objectInSet isKindOfClass:[MyClass class]]) {
    [(MyClass *)cell myClassMethod];
}

but because NSSet is a set of NSObject it could contain different types of objects (derived from NSObject), so asking the NSSet what kinds of object it contains is kind of pointless because it would always tell you NSObject.


The use of the word "touch" in the label is a pretty big clue that it's a UITouch, but if you want to know unambiguously what a method does, the obvious thing to do is check the documentation. Let's see what it says for that method:

touches

A set of UITouch instances that represent the touches that are moving during the event represented by event.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜