Ser Pounce
Ser Pounce

Reputation: 14553

Possible to cast when sending a message in objective-c?

I have:

[[[[self navigationItem] leftBarButtonItem] customView] setTitle:@" Create "];

Which is triggering a warning "'UIView' may not respond to '-setTitle:'". I've tried:

[[[[self navigationItem] leftBarButtonItem] (UIButton*)customView] setTitle:@" Create "];

And get errors when I do this. 0I also tried casting with (id) and that didn't work either. I know I could probably just store the customView in a UIButton and go from there, but just wondering if it's possible to cast within a message like this?

Upvotes: 0

Views: 145

Answers (2)

kra
kra

Reputation: 131

Like said earlier, it would be wise to check for the concrete class of customView or if the instance respondsToSelector, otherwise you're likely to experience crashes should that particular view change for whatever reason. Otherwise, using the dot notation (all of these are actually properties) for this kind of nesting will make your code a lot more readable?

Upvotes: 0

PengOne
PengOne

Reputation: 48398

Think about what you are casting. Try this

[(UIButton*)[[[self navigationItem] leftBarButtonItem] customView] setTitle:@" Create "];

The difference in this line and your line is that you should not cast a property (e.g. customView) but rather the returned object on which you are about to call a method.

Upvotes: 5

Related Questions