Nairam
Nairam

Reputation: 285

Properly casting when sending nested messages

Getting the text property of a UITextView from a childViewController like this:

NSString *text = [((UITextField *)[[childViewController view]viewWithTag:0])text];

seems to be fine with Xcode. However, as soon as the app runs and the method is called, I get an uncaught exception 'NSInvalidArgumentException', reason: '-[UIView text]: unrecognized selector sent to instance 0x89763f0' I think there's something wrong the way I cast to an UITextField.
I already tried several other ways to cast this, but they are always giving me errors in Xcode, so I guess this is the closest I got to the solution.
Does anybody know how to cast this properly?
Thanks for your help!

Upvotes: 1

Views: 44

Answers (3)

mithlesh jha
mithlesh jha

Reputation: 343

For your code following should work for you.

NSString *text = nil;
for (id subview in [childViewController view] subviews]){
    if ([subview isKindOfClass:[UITextField class]]){
        text = [(UITextField*)subview text];
        break;
    }
}

However if a specific subviews of a view is to be accessed frequently, their tag should be set to unique values as suggested in other replies too.

Upvotes: 0

Droppy
Droppy

Reputation: 9721

There is nothing wrong with the code, apart from being difficult to read (and therefore to maintain), however you will need to add some checks to see if the view you think is a UITextField is in fact one:

UITextField *textField = [[childViewController view] viewWithTag:0];
NSAssert([textField isKindOfClass:[UITextField class]], @"Oh no! I was wrong");
NSString *text = textField.text;

I would suggest tag 0 is a bad number to choose as that's the default (unset) value and I would expect that assert to fire.

Upvotes: 1

Midhun MP
Midhun MP

Reputation: 107141

It is nothing related to the casting.

It is actually with the tag value. Default tag value is 0, so if you do like that, it won't give UITextField. It can give any views for that you won't set tag.

Upvotes: 0

Related Questions