views:

64

answers:

3

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 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?

A: 

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.

Aran Mulholland
It's what I sometimes don't like in Obj-C, I miss generics in Java and C#
vodkhang
@vodkhang Cocoa design patterns do not use patterns that would require generics. Thus, the lack of generics isn't really an issue if you follow said design patterns.
bbum
+7  A: 

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.

bbum
yep, you are right in terms of cocoa. the only place i have used it is when i have a table view that has different kinds of custom UITableViewCells. (so it is still useful to know the answer in those edge cases)
Aran Mulholland
If you have different kinds of custom UITableViewCells, the common practice would be to have a method that allows for differentiation based on attribute or behavior, separating the decision from the class hierarchy.
bbum
Not that using isKindOfClass: is wrong... it is just, well, the odd pattern in this context.
bbum
A: 

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.

Chuck