简体   繁体   English

比较一个空的UITextField与nil字符串

[英]Compare an empty UITextField to nil string

I have a UITextField that I am trying to compare to a string password in a class. 我有一个UITextField,试图将其与类中的字符串密码进行比较。 The problem happens when the password is nil. 密码为nil时会发生问题。 According to the debugger an empty UITextField returns @"" so I tried a length based appproach. 根据调试器,空的UITextField返回@""因此我尝试了基于长度的appproach。

 NSString *pw;
 if([[alertView textFieldAtIndex:1].text length] > 0)
     pw = room.password;

 if([pw isEqualToString:room.password])
  //do some code

But this still isn't working for nil passwords...ive even verified with the debugger that both pw and room.password are nil (see below)...whats going on? 但这对于nil密码仍然不起作用...甚至通过调试器验证了pwroom.password均为nil (请参见下文)...怎么回事?

在此处输入图片说明

The problem is that you're sending a message to nil. 问题是您正在向nil发送一条消息。 That's never going to return TRUE. 那永远不会返回TRUE。

pw can't respond to the isEqualToString: selector because it's nil. pw无法响应isEqualToString:选择器,因为它为nil。

You can send any message to a nil object. 您可以将任何消息发送到nil对象。

"If you expect a return value from a message sent to nil, the return value will be nil for object return types, 0 for numeric types, and NO for BOOL types. Returned structures have all members initialized to zero." “如果期望从发送到nil的消息返回值,则对象返回类型的返回值为nil,数字类型的返回值为0,BOOL类型的返回值为NO。返回的结构会将所有成员初始化为零。” - Source: https://developer.apple.com/library/ios/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/WorkingwithObjects/WorkingwithObjects.html -来源: https//developer.apple.com/library/ios/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/WorkingwithObjects/WorkingwithObjects.html

Since pw is nil keep in mind, that there are no isEqual methods declared for that object. 请记住,由于pwnil ,因此没有为该对象声明isEqual方法。

Therefore, what you should do is: 因此,您应该做的是:

if([pw isEqualToString:room.password] || (pw == nil && room.password == nil))

Try this: 尝试这个:

UITextField *textField = [alertView textFieldAtIndex:1];
if (textField.text == nil) {
    //empty textField
    DoSomething();
} else {
    //textField contains text
    DoSomethingElse();
}

如果强为零,则该强不存在,因此您无法进行比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM