I got this code and XCode warns me of "incompatible pointer types initializing NSString *__strong with an expression of type UITextField".
NSString *name = (UITextField *)searchText.text;
but this one is fine
NSString *name2 = [(UITextField *)searchText text];
and this one is fine too
NSString *name3 = [(UITextField *)searchText.text mutableCopy];
I have two questions:
obj.*
and [obj *]
I don't know how to search in Apple developer documentation for these questions.
In the first version, due to operator precedence, you're casting searchText.text
to a UITextField*
, what you want to do is probably to cast searchText
;
NSString *name = ((UITextField *)searchText).text;
In the second version you don't have the dot, so the compiler understands your cast to be casting searchText to UITextField
and send the text message to it. In other words, exactly right.
The last case is a bit tricky since it involves both runtime and compile time. As I understand it;
searchText.text
to a UITextField*
. The runtime still knows that the object is an NSString and the mutableCopy
message that exists on both will go to the correct method [NSString mutableCopy] anyway and create/return a mutable copy of the NSString so runtime it works out ok.mutableCopy
returns id
(referencing a NSMutableString), the assignment to an NSString is ok by the compiler (id can be assigned to anything), so compile time it's ok.A question, what is searchText
originally? That the last version compiled without warning indicates that it's already an UITextField*
, or at least a type that can take the text
message. If so, you should be able to just do;
NSString *name3 = [searchText.text mutableCopy];
In the second and third examples, the cast just operates on searchText. So with these you are sending a message to a UITextField object.
In the first one, the cast applies to the whole of searchText.text. Assigning a UITextField object to a NSString variables is not what you want. The code you're looking for is:
NSString *name = ((UITextField *)searchText).text;
The mutableCopy message returns a copy of your string as a NSMutableString object, which can be assigned to a NSString as NSMutableString derives from it. In this case using the 'copy' message is just as good.
Hope that helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With