0

I have an array that may have objects of "Theme" class or "Language" class. Now I am Type Casting my method to Theme class manually. I want to check If array have objects of Theme class then Type cast it with Theme

    cell.textLabel.text = [NSString stringWithFormat:@"%@",[(Theme *)[_listArray objectAtIndex:indexPath.row] name]];

_listArray may also objects of Language Class.

I have done

Class theClass  = [[_listArray firstObject] class];

    cell.textLabel.text = [NSString stringWithFormat:@"%@",[(theClass *)[_listArray objectAtIndex:indexPath.row] name]];

But it is not working...!!! How should I do this?

Thanks.

1 Answer 1

1

First, it is not necessary to type cast id objects stored in NSArray to a specific type before sending it the message name. This will compile as well:

cell.textLabel.text = [NSString stringWithFormat:@"%@",[[_listArray objectAtIndex:indexPath.row] name]];

However, you would get a run-time problem if the corresponding element does not respond to selector name. Here is how:

NSObject *item = [_listArray objectAtIndex:indexPath.row];
if ([item respondsToSelector:@selector(name)]) {
    cell.textLabel.text = [NSString stringWithFormat:@"%@",[item name]];
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.