ios NSString 为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3436173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NSString is empty
提问by Yazzmi
How do you test if an NSString is empty? or all whitespace or nil? with a single method call?
你如何测试一个 NSString 是否为空?或所有空白或零?使用单个方法调用?
回答by Jacob Relkin
You can try something like this:
你可以尝试这样的事情:
@implementation NSString (JRAdditions)
+ (BOOL)isStringEmpty:(NSString *)string {
if([string length] == 0) { //string is empty or nil
return YES;
}
if(![[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]) {
//string is all whitespace
return YES;
}
return NO;
}
@end
Check out the NSString
reference on ADC.
查看NSString
ADC 上的参考资料。
回答by scooter133
This is what I use, an Extension to NSString:
这就是我使用的,NSString 的扩展:
+ (BOOL)isEmptyString:(NSString *)string;
// Returns YES if the string is nil or equal to @""
{
// Note that [string length] == 0 can be false when [string isEqualToString:@""] is true, because these are Unicode strings.
if (((NSNull *) string == [NSNull null]) || (string == nil) ) {
return YES;
}
string = [string stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ([string isEqualToString:@""]) {
return YES;
}
return NO;
}
回答by karim
I use,
我用,
+ (BOOL ) stringIsEmpty:(NSString *) aString {
if ((NSNull *) aString == [NSNull null]) {
return YES;
}
if (aString == nil) {
return YES;
} else if ([aString length] == 0) {
return YES;
} else {
aString = [aString stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ([aString length] == 0) {
return YES;
}
}
return NO;
}
+ (BOOL ) stringIsEmpty:(NSString *) aString shouldCleanWhiteSpace:(BOOL)cleanWhileSpace {
if ((NSNull *) aString == [NSNull null]) {
return YES;
}
if (aString == nil) {
return YES;
} else if ([aString length] == 0) {
return YES;
}
if (cleanWhileSpace) {
aString = [aString stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ([aString length] == 0) {
return YES;
}
}
return NO;
}
回答by Josh Bruce
I hate to throw another log on this exceptionally old fire, but I'm leery about editing someone else's answer - especially when it's the selected answer.
我讨厌在这个异常古老的火上再写一份日志,但我对编辑别人的答案持怀疑态度 - 特别是当它是选定的答案时。
Jacob asked a follow up question: How can I do this with a single method call?
Jacob 提出了一个后续问题:我如何通过单个方法调用来做到这一点?
The answer is, by creating a category - which basically extends the functionality of a base Objective-C class - and writing a "shorthand" method for all the other code.
答案是,通过创建一个类别——它基本上扩展了基础 Objective-C 类的功能——并为所有其他代码编写了一个“速记”方法。
However, technically, a string with white space characters is not empty - it just doesn't contain any visible glyphs (for the last couple of years I've been using a method called isEmptyString: and converted today after reading this question, answer, and comment set).
然而,从技术上讲,带有空格字符的字符串不是空的——它只是不包含任何可见的字形(在过去的几年里,我一直在使用一种名为 isEmptyString: 的方法,并在阅读了这个问题后今天转换了,回答,和评论集)。
To create a category go to Option+Click -> New File... (or File -> New -> File... or just command+n) -> choose Objective-C Category. Pick a name for the category (this will help namespace it and reduce possible future conflicts) - choose NSString from the "Category on" drop down - save the file somewhere. (Note: The file will automatically be named NSString+YourCategoryName.h and .m.)
要创建类别,请转到 Option+Click -> New File...(或 File -> New -> File... 或只是 command+n)-> 选择 Objective-C Category。挑选类别的名称(这将有助于它的命名空间以及减少未来可能发生的冲突) - 从“上目录”选择的NSString下拉 - 保存文件的某处。(注意:文件将自动命名为 NSString+YourCategoryName.h 和 .m。)
I personally appreciate the self-documenting nature of Objective-C; therefore, I have created the following category method on NSString modifying my original isEmptyString: method and opting for a more aptly declared method (I trust the compiler to compress the code later - maybe a little too much).
我个人很欣赏 Objective-C 的自我记录特性;因此,我在 NSString 上创建了以下类别方法,修改了我原来的 isEmptyString: 方法并选择了一个更恰当地声明的方法(我相信编译器稍后会压缩代码 - 可能有点太多了)。
Header (.h):
标题 (.h):
#import <Foundation/Foundation.h>
@interface NSString (YourCategoryName)
/*! Strips the string of white space characters (inlcuding new line characters).
@param string NSString object to be tested - if passed nil or @"" return will
be negative
@return BOOL if modified string length is greater than 0, returns YES;
otherwise, returns NO */
+ (BOOL)visibleGlyphsExistInString:(NSString *)string;
@end
Implementation (.m):
实施(.m):
@implementation NSString (YourCategoryName)
+ (BOOL)visibleGlyphsExistInString:(NSString *)string
{
// copying string should ensure retain count does not increase
// it was a recommendation I saw somewhere (I think on stack),
// made sense, but not sure if still necessary/recommended with ARC
NSString *copy = [string copy];
// assume the string has visible glyphs
BOOL visibleGlyphsExist = YES;
if (
copy == nil
|| copy.length == 0
|| [[copy stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0
) {
// if the string is nil, no visible characters would exist
// if the string length is 0, no visible characters would exist
// and, of course, if the length after stripping the white space
// is 0, the string contains no visible glyphs
visibleGlyphsExist = NO;
}
return visibleGlyphsExist;
}
@end
To call the method be sure to #import the NSString+MyCategoryName.h file into the .h or .m (I prefer the .m for categories) class where you are running this sort of validation and do the following:
要调用该方法,请务必将 NSString+MyCategoryName.h 文件 #import 到 .h 或 .m(我更喜欢使用 .m 表示类别)类中,在其中运行此类验证并执行以下操作:
NSString* myString = @""; // or nil, or tabs, or spaces, or something else
BOOL hasGlyphs = [NSString visibleGlyphsExistInString:myString];
Hopefully that covers all the bases. I remember when I first started developing for Objective-C the category thing was one of those "huh?" ordeals for me - but now I use them quite a bit to increase reusability.
希望这涵盖了所有的基础。我记得当我第一次开始为 Objective-C 开发时,类别就是其中之一,“嗯?” 对我的考验 - 但现在我使用它们来提高可重用性。
Edit: And I suppose, technically, if we're stripping characters, this:
编辑:而且我想,从技术上讲,如果我们要剥离字符,则为:
[[copy stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0
Is really all that is needed (it should do everything that category method does, including the copy), but I could be wrong on that score.
真的是所有需要的(它应该完成类别方法所做的一切,包括副本),但我在这方面可能是错误的。
回答by Cherpak Evgeny
I'm using this define as it works with nil strings as well as empty strings:
我正在使用这个定义,因为它适用于 nil 字符串以及空字符串:
#define STR_EMPTY(str) \
str.length == 0
Actually now its like this:
其实现在是这样的:
#define STR_EMPTY(str) \
(![str isKindOfClass:[NSString class]] || str.length == 0)
回答by pvllnspk
Based on the Jacob Relkin answer and Jonathan comment:
基于 Jacob Relkin 的回答和 Jonathan 的评论:
@implementation TextUtils
+ (BOOL)isEmpty:(NSString*) string {
if([string length] == 0 || ![[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]) {
return YES;
}
return NO;
}
@end
回答by MCKapur
Should be easier:
应该更容易:
if (![[string stringByReplacingOccurencesOfString:@" " withString:@""] length]) { NSLog(@"This string is empty"); }
回答by liushuaikobe
Maybe you can try something like this:
也许你可以尝试这样的事情:
+ (BOOL)stringIsEmpty:(NSString *)str
{
return (str == nil) || (([str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]).length == 0);
}