Objective C 检查文本字段是否为空
这是代码:
- (IBAction) charlieInputText:(id)sender {
//getting value from text field when entered
charlieInputSelf = [sender stringValue];
if (charlieInputSelf != @"") {
//(send field if not empty
}
}
即使字段为空,也会发送它;因此,这并不像我想要的那样工作。
Here's the code:
- (IBAction) charlieInputText:(id)sender {
//getting value from text field when entered
charlieInputSelf = [sender stringValue];
if (charlieInputSelf != @"") {
//(send field if not empty
}
}
This sends it even when the field is empty; therefore, this does not work as I want it to.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
只需检查 nil 以及文本长度是否大于 0 - 非空
Simply checks for nil and if length of text length is greater than 0 - not empty
我们已经有内置方法返回布尔值,指示文本输入对象是否有任何文本。
We already have inbuilt method that return boolean value that indicates whether the text-entry objects has any text or not.
Joshua 在狭隘的情况下有正确的答案,但一般来说,您不能使用 == 或 != 运算符来比较字符串对象。您必须使用
-isEqual:
或-isEqualToString:
这是因为charlieImputSelf
和@""
实际上是指向对象。尽管两个字符序列可能相同,但它们不必指向内存中的同一位置。Joshua has the right answer in the narrow case, but generally, you can't compare string objects using the == or != operators. You must use
-isEqual:
or-isEqualToString:
This is becausecharlieImputSelf
and@""
are actually pointers to objects. Although the two sequences of characters may be the same, they need not point at the same location in memory.这些在某种程度上“起作用”。但是,我发现用户只需在框中填写空格即可。我发现使用正则表达式有帮助(尽管我使用的是没有空格的单词)我真的不知道如何允许空格。
Those 'work' in a way. However, I found that the user can just fill in the box with spaces. I found using regular expressions helps (though what I use is for words without spaces) I can't really figure out how to make allow spaces.
最有效的方法是使用这个
The Most efficent way to do this is by using this
检查 Swift 中的文本字段是否为空
Check whether text field is empty in Swift
最简单的方法。
创建不带“”(空格)的新 NSString
现在您有了不带空格的字符串。
您只需检查该字符串是否为空。
The easiest way to do it.
Create new NSString without " " (spaces)
Now you have string without spaces.
You just have to check is this string empty or not.