views:

486

answers:

2

Hey guys,

I was wondering how it can be that iterating through an NSMutableArray works, but when I call objectAtIndex it fails with "*** -[NSCFSet objectAtIndex:]: unrecognized selector sent to instance 0x..."

Here is some sample code, the program is too big to share in whole so I hope it's enough. The code is executed in the latest iPhone Simulator from XCode.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 RDLogString(@"Creating cell @ row no. %d", indexPath.row);
 CPPlayerAppDelegate * appDelegate = [[UIApplication sharedApplication] delegate];
 RDLogString(@"Conversations: %p. Item count: %d", appDelegate.distribution.conversations, appDelegate.distribution.conversations.count);  
 //This works  
 for(CPConversation * x in appDelegate.distribution.conversations){
  RDLogString(@"Pointer: %p with name %@", x, x.name);
 }  
 //This fails with aforementioned error  
 CPConversation * conversationAtCurrentIndex = [appDelegate.distribution.conversations objectAtIndex: indexPath.row];

Sorry for the bad formatting, still figuring it out. :)

Thanks in advance, Nick

+1  A: 

objectAtIndex: is part of NSArray, not NSSet. This means your appDelegate.distribution.conversations is returning an NSSet and you need an NSArray.

Dave DeLong
Thanks to both! I had defined it as an NSMutableArray, but further I initialized it with [[NSMutableSet alloc] init]; xDSometimes I miss C(++)'s static typing. It must've been a warning but I got so many... I need to pay more attention to those. Anyhow, thanks a lot.
Nick
Aye, no edit. It's not even a warning. Just got to be careful I guess. Any suggestions to spot such errors?
Nick
The problem is that NSMutableArray's designated initializer -- along with NSSet and NSDictionary -- are declared as returning (id) and, thus, any method on any class is considered valid. The reason they are declared that way is because Objective-C doesn't support covariant declarations.
bbum
As long as you avoid the (id) type, though, Objective-C does a fine job of supporting static type analysis (which I meant to add to the previous comment).
bbum
A: 

That exception message is telling you that you're sending a message with a selector that the receiving class doesn't recognize or respond to. In this case, you're sending a objectAtIndex: message to an object of type NSCFSet (or just NSSet).

This means that whatever appDelegate.distribution.conversations is, you're expecting it to be an NSArray, but its actually an NSSet. How are you creating the object accessed there?

Sbrocket