Friday, June 14, 2013

NSCharacterSet whitespaceAndNewlineCharacterSet example in Objective C (iOS).


NSCharacterSet whitespaceAndNewlineCharacterSet

Returns a character set containing only the whitespace characters space (U+0020) and tab (U+0009) and the newline and nextline characters (U+000A–U+000D, U+0085).

+ (id)whitespaceAndNewlineCharacterSet

Return Value of [NSCharacterSet whitespaceAndNewlineCharacterSet]
A character set containing only the whitespace characters space (U+0020) and tab (U+0009) and the newline and nextline characters (U+000A–U+000D, U+0085).

NSCharacterSet whitespaceAndNewlineCharacterSet example.
 NSCharacterSet *dontWantChar = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    NSString *string = [[self.textView.text componentsSeparatedByCharactersInSet:dontWantChar] componentsJoinedByString:@""];

Example of [NSCharacterSet whitespaceAndNewlineCharacterSet].
str = [aSearchBar.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
str = [str retain]; // Keep object alive beyond the scope of this method
Of course if you keep an object alive like this, you must release it yourself somewhere in your code. So if you want this variable to be overridden each time the method is called, use

[str release];
str = [aSearchBar.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
str = [str retain]; // Keep object alive beyond the scope of this method

NSCharacterSet whitespaceAndNewlineCharacterSet example.
NSString *string = @" spaces in front and at the end ";
NSString *trimmedString = [string stringByTrimmingCharactersInSet:
                                  [NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(@"%@", trimmedString)

End of NSCharacterSet whitespaceAndNewlineCharacterSet example article.