Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warning - incompatible pointer types initializing 'NSString *__strong' with an expression of type 'UITextField'

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:

  1. I am confused with obj.* and [obj *]
  2. Why is the "mutableCopy" correct is this case?

I don't know how to search in Apple developer documentation for these questions.

like image 866
rock Avatar asked Mar 19 '12 17:03

rock


2 Answers

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;

  • You cast 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.
  • Since 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];
like image 78
Joachim Isaksson Avatar answered Nov 12 '22 01:11

Joachim Isaksson


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.

like image 39
Cthutu Avatar answered Nov 12 '22 00:11

Cthutu