Method To Delete 2nd Label, Then First Label, Not Functioning Correctly

后端 未结 4 2038
心在旅途
心在旅途 2021-01-25 11:21

I know I am missing something obvious, but I just cannot see it. This method is meant to compare the text of a label to the text of a text box, and then delete the text. So if t

相关标签:
4条回答
  • 2021-01-25 11:29

    Compairing String literals using == is not guaranteed to behave as you might expect. Use isEqual: or isEqualToString: instead.

    See http://nshipster.com/equality/.

    0 讨论(0)
  • 2021-01-25 11:33

    When you are comparing NSStrings with == what you are actually comparing are two memory addresses and that is not what you are really intended for. You want to compare the values of two strings what == operator is not suitable for and thus you are getting the warning

    Direct comparison of a string literal has undefined behavior.

    To compare the values of NSStrings you should use isEqualToString: method. You could have also use isEqual: method derived from NSObject class but that is not suitable for Unicode comparison. So isEqualToString: is always the safest bet.

    After using isEqualToString: your code should look something like:

    -(IBAction)btnDelete:(id)sender
    {
      if ([self.lblFabric2.text isEqualToString:self.txtType.text])
       {
         self.lblFabric2.text = @"";
       }
      else
       {
         self.lblFabric1.text=@"";
       }
    }
    
    0 讨论(0)
  • 2021-01-25 11:35

    You should not use == or != for string comparison in Objective C. You need to use the isEqualToString or isEqual method.

    if (([self.lblFabric2.text isEqualToString:self.txtType.text]))
    

    When you use == or != you are comparing the pointers where the strings are stored.

    0 讨论(0)
  • 2021-01-25 11:42

    To compare NSStrings use:

    if ([myString1 isEqualToString:myString2])
    

    Documentation

    0 讨论(0)
提交回复
热议问题