How do you test if an NSString is empty? or all whitespace or nil? with a single method call?
相关问题
- CALayer - backgroundColor flipped?
- how to split a list into a given number of sub-lis
- Core Data lightweight migration crashes after App
- Core Data lightweight migration crashes after App
- How can I implement password recovery in an iPhone
相关文章
- 现在使用swift开发ios应用好还是swift?
- JSP String formatting Truncate
- UITableView dragging distance with UIRefreshContro
- Could I create “Call” button in HTML 5 IPhone appl
- TCC __TCCAccessRequest_block_invoke
- Where does a host app handle NSExtensionContext#co
- xcode 4 garbage collection removed?
- Selecting only the first few characters in a strin
I'm using this define as it works with nil strings as well as empty strings:
Actually now its like this:
This is what I use, an Extension to NSString:
I use,
Maybe you can try something like this:
You can try something like this:
Check out the
NSString
reference on ADC.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?
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.
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).
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.)
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).
Header (.h):
Implementation (.m):
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:
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.
Edit: And I suppose, technically, if we're stripping characters, this:
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.