Friday, June 14, 2013

NSCharacterSet longCharacterIsMember example in Objective C (iOS).


NSCharacterSet longCharacterIsMember

Returns a Boolean value that indicates whether a given long character is a member of the receiver.

- (BOOL)longCharacterIsMember:(UTF32Char)theLongChar

Parameters of [NSCharacterSet longCharacterIsMember]
theLongChar
A UTF32 character.

Return Value
YES if theLongChar is in the receiver, otherwise NO.

Discussion of [NSCharacterSet longCharacterIsMember]
This method supports the specification of 32-bit characters.

NSCharacterSet longCharacterIsMember example.
NSCharacterSet *charset = [NSCharacterSet uppercaseLetterCharacterSet];
NSMutableArray *array = [NSMutableArray array];
for (int plane = 0; plane <= 16; plane++) {
    if ([charset hasMemberInPlane:plane]) {
        UTF32Char c;
        for (c = plane << 16; c < (plane+1) << 16; c++) {
            if ([charset longCharacterIsMember:c]) {
                UTF32Char c1 = OSSwapHostToLittleInt32(c); // To make it byte-order safe
                NSString *s = [[NSString alloc] initWithBytes:&c1 length:4 encoding:NSUTF32LittleEndianStringEncoding];
                [array addObject:s];
            }
        }
    }
}

End of NSCharacterSet longCharacterIsMember example article.

NSCharacterSet isSupersetOfSet example in Objective C (iOS).


NSCharacterSet isSupersetOfSet

Returns a Boolean value that indicates whether the receiver is a superset of another given character set.

- (BOOL)isSupersetOfSet:(NSCharacterSet *)theOtherSet

Parameters of [NSCharacterSet isSupersetOfSet]
theOtherSet
A character set.

Return Value of [NSCharacterSet isSupersetOfSet]
YES if the receiver is a superset of theOtherSet, otherwise NO.

NSCharacterSet isSupersetOfSet example.
#pragma mark - UItextfield Delegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([string isEqualToString:@"("]||[string isEqualToString:@")"]) {
        return TRUE;
    }

    NSLog(@"Range ==%d  ,%d",range.length,range.location);
    //NSRange *CURRANGE = [NSString  rangeOfString:string];

    if (range.location == 0 && range.length == 0) {
        if ([string isEqualToString:@"+"]) {
            return TRUE;
        }
    }
    return [self isNumeric:string];
}

-(BOOL)isNumeric:(NSString*)inputString{
    BOOL isValid = NO;
    NSCharacterSet *alphaNumbersSet = [NSCharacterSet decimalDigitCharacterSet];
    NSCharacterSet *stringSet = [NSCharacterSet characterSetWithCharactersInString:inputString];
    isValid = [alphaNumbersSet isSupersetOfSet:stringSet];
    return isValid;
}

Example of [NSCharacterSet isSupersetOfSet].
BOOL valid;
NSCharacterSet *alphaNums = [NSCharacterSet decimalDigitCharacterSet];
NSCharacterSet *inStringSet = [NSCharacterSet characterSetWithCharactersInString:myInputField.text];
valid = [alphaNums isSupersetOfSet:inStringSet];   
if (!valid) // Not numeric

NSCharacterSet isSupersetOfSet example.
NSRegularExpression *numEx = [NSRegularExpression
    regularExpressionWithPattern:@"^[-+]?[0-9]+$" options:0 error:nil
];
NSLog(@"%ld", [numEx numberOfMatchesInString:@"-200" options:0 range:NSMakeRange(0, 4)]);
NSLog(@"%ld", [numEx numberOfMatchesInString:@"001A" options:0 range:NSMakeRange(0, 4)]);
For character set, use [NSCharacterSet decimalDigitCharacterSet].

BOOL isNum = [[NSCharacterSet decimalDigitCharacterSet]
    isSupersetOfSet:[NSCharacterSet characterSetWithCharactersInString:@"001AA"]
];

End of NSCharacterSet isSupersetOfSet example article.

NSCharacterSet invertedSet example in Objective C (iOS).


NSCharacterSet invertedSet

Returns a character set containing only characters that don’t exist in the receiver.

- (NSCharacterSet *)invertedSet

Return Value
A character set containing only characters that don’t exist in the receiver.

Discussion of [NSCharacterSet invertedSet]
Inverting an immutable character set is much more efficient than inverting a mutable character set.

NSCharacterSet invertedSet example.
NSMutableCharacterSet *mcs = [[[NSCharacterSet letterCharacterSet] invertedSet] mutableCopy];
[mcs removeCharactersInString:@"<characters you want excluded>"];

myString = [[myString componentsSeparatedByCharactersInSet:mcs] componentsJoinedByString:@""];

[mcs release];

Example of [NSCharacterSet invertedSet].
NSMutableCharacterSet *charactersToKeep = [NSMutableCharacterSet alphanumericCharacterSet];
[charactersToKeep addCharactersInString:@" ,."];

NSCharacterSet *charactersToRemove = [charactersToKeep invertedSet];

NSString *trimmedReplacement = [[ str componentsSeparatedByCharactersInSet:charactersToRemove] componentsJoinedByString:@"" ];

NSCharacterSet invertedSet example.
NSCharacterSet * set = [[NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ0123456789"] invertedSet];

if ([aString rangeOfCharacterFromSet:set].location != NSNotFound) {
  NSLog(@"This string contains illegal characters");
}
You could also use a regex (this syntax is from RegexKitLite: http://regexkit.sourceforge.net ):

if ([aString isMatchedByRegex:@"[^a-zA-Z0-9]"]) {
  NSLog(@"This string contains illegal characters");
}

End of NSCharacterSet invertedSet example article.

NSCharacterSet hasMemberInPlane example in Objective C (iOS).


NSCharacterSet hasMemberInPlane

Returns a Boolean value that indicates whether the receiver has at least one member in a given character plane.

- (BOOL)hasMemberInPlane:(uint8_t)thePlane

Parameters of [NSCharacterSet hasMemberInPlane]
thePlane
A character plane.

Return Value
YES if the receiver has at least one member in thePlane, otherwise NO.

Discussion of [NSCharacterSet hasMemberInPlane]
This method makes it easier to find the plane containing the members of the current character set. The Basic Multilingual Plane is plane 0.

NSCharacterSet hasMemberInPlane example.
NSCharacterSet *charset = [NSCharacterSet uppercaseLetterCharacterSet];
NSMutableArray *array = [NSMutableArray array];
for (int plane = 0; plane <= 16; plane++) {
    if ([charset hasMemberInPlane:plane]) {
        UTF32Char c;
        for (c = plane << 16; c < (plane+1) << 16; c++) {
            if ([charset longCharacterIsMember:c]) {
                UTF32Char c1 = OSSwapHostToLittleInt32(c); // To make it byte-order safe
                NSString *s = [[NSString alloc] initWithBytes:&c1 length:4 encoding:NSUTF32LittleEndianStringEncoding];
                [array addObject:s];
            }
        }
    }
}

End of NSCharacterSet hasMemberInPlane example article.

NSCharacterSet characterIsMember example in Objective C (iOS).


NSCharacterSet characterIsMember

Returns a Boolean value that indicates whether a given character is in the receiver.

- (BOOL)characterIsMember:(unichar)aCharacter

Parameters
aCharacter
The character to test for membership of the receiver.

Return Value of [NSCharacterSet characterIsMember]
YES if aCharacter is in the receiving character set, otherwise NO.

NSCharacterSet characterIsMember example.
To eliminate non letters:

NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
NSCharacterSet *notLetters = [[NSCharacterSet characterSetWithCharactersInString:letters] invertedSet];
NSString *newString = [[string componentsSeparatedByCharactersInSet:notLetters] componentsJoinedByString:@""];
To check one character at a time:

for (int i = 0; i < [string length]; i++) {
    unichar c = [string characterAtIndex:i];
    if ([notLetters characterIsMember:c]) {
       ...
    }
}

Example of [NSCharacterSet characterIsMember].
To see if your 'substring' variable in one of your sets you would do:

if ([substring rangeOfCharacterFromSet:setOne].location != NSNotFound) {
    // substring is in setOne
} else if ([substring rangeOfCharacterFromSet:setTwo].location != NSNotFound) {
    // substring is in setTwo
}
Another option is to work with characters.

for (int i = 0; i<[word length]; i++) {
    unichar ch = [word characterAtIndex:i];

    if ([setOne characterIsMember:ch]) {
        // in setOne
    } else if ([setTwo characterIsMember:ch]) {
        // in setTwo
    }
}

NSCharacterSet characterIsMember example.
- (BOOL) textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)textEntered
{
    for (int i = 0; i < [textEntered length]; i++)
    {
        unichar c = [textEntered characterAtIndex:i];
        if ([disallowedCharacters characterIsMember:c])
        {
            return NO;
        }
    }
    return YES;
}

End of NSCharacterSet characterIsMember example article.

NSCharacterSet bitmapRepresentation example in Objective C (iOS).


NSCharacterSet bitmapRepresentation

Returns an NSData object encoding the receiver in binary format.

- (NSData *)bitmapRepresentation

Return Value
An NSData object encoding the receiver in binary format.

Discussion of [NSCharacterSet bitmapRepresentation]
This format is suitable for saving to a file or otherwise transmitting or archiving.

A raw bitmap representation of a character set is a byte array of 2^16 bits (that is, 8192 bytes). The value of the bit at position n represents the presence in the character set of the character with decimal Unicode value n. To test for the presence of a character with decimal Unicode value n in a raw bitmap representation, use an expression such as the following:

unsigned char bitmapRep[8192];
if (bitmapRep[n >> 3] & (((unsigned int)1) << (n & 7))) {
/* Character is present. */
}

NSCharacterSet bitmapRepresentation example.
@interface StringWrapper : NSObject
@property (nonatomic, copy) NSString *string;
@property (nonatomic, copy) NSData *charSetBitmap;
- (id)initWithString:(NSString*)aString;
@end

@implementation StringWrapper
@synthesize string, charSetBitmap;

- (id)initWithString:(NSString*)aString;
{
    if ((self = [super init]))
    {
        self.string = aString;
    }
    return self;
}

- (void)setString:(NSString *)aString;
{
    string = [aString copy];
    self.charSetBitmap = [[NSCharacterSet characterSetWithCharactersInString:aString] bitmapRepresentation];
}

- (BOOL)isEqual:(id)object;
{
    return [self.charSetBitmap isEqual:[object charSetBitmap]];
}

- (NSUInteger)hash;
{
    return [self.charSetBitmap hash];
}

Example of [NSCharacterSet bitmapRepresentation].
// this doesn't seem to be available
#define UNICHAR_MAX (1 << (CHAR_BIT * sizeof(unichar) - 1))

NSData *data = [[NSCharacterSet uppercaseLetterCharacterSet] bitmapRepresentation];
uint8_t *ptr = [data bytes];
NSMutableArray *allCharsInSet = [NSMutableArray array];
// following from Apple's sample code
for (unichar i = 0; i < UNICHAR_MAX; i++) {
    if (ptr[i >> 3] & (((unsigned int)1) << (i & 7))) {
        [allCharsInSet addObject:[NSString stringWithCharacters:&i length:1]];
    }
}

NSCharacterSet bitmapRepresentation example.
NSArray * charactersInCharacterSet(NSCharacterSet *charSet)
{
  NSMutableArray * array = [NSMutableArray array];
  NSData * data = [charSet bitmapRepresentation];
  const char* bytes = [data bytes];

  for (int i = 0; i < 8192; ++i)
  {
    if (bytes[i >> 3] & (((unsigned int)1) << (i & 7)))
    {
      [array addObject:[NSString stringWithFormat:@"%C", i]];
    }
  }
  return [NSArray arrayWithArray:array];
}

NSCharacterSet * charSet = [[[[NSLocale alloc] initWithLocaleIdentifier:@"sr_Cyrl_ME"] autorelease] objectForKey:NSLocaleExemplarCharacterSet];
NSArray * chars = charactersInCharacterSet(charSet);
for (NSString *str in chars)
{
  NSLog(@"%@", str);
}

End of NSCharacterSet bitmapRepresentation example article.

NSCharacterSet whitespaceCharacterSet example in Objective C (iOS).


NSCharacterSet whitespaceCharacterSet

Returns a character set containing only the in-line whitespace characters space (U+0020) and tab (U+0009).

+ (id)whitespaceCharacterSet

Return Value
A character set containing only the in-line whitespace characters space (U+0020) and tab (U+0009).

Discussion of [NSCharacterSet whitespaceCharacterSet]
This set doesn’t contain the newline or carriage return characters.

NSCharacterSet whitespaceCharacterSet example.
NSString *theString = @"    Hello      this  is a   long       string!   ";

NSCharacterSet *whitespaces = [NSCharacterSet whitespaceCharacterSet];
NSPredicate *noEmptyStrings = [NSPredicate predicateWithFormat:@"SELF != ''"];

NSArray *parts = [theString componentsSeparatedByCharactersInSet:whitespaces];
NSArray *filteredArray = [parts filteredArrayUsingPredicate:noEmptyStrings];
theString = [filteredArray componentsJoinedByString:@" "];

Example of [NSCharacterSet whitespaceCharacterSet].
There is method for that in NSString class. Check stringByTrimmingCharactersInSet:(NSCharacterSet *)set. You should use [NSCharacterSet whitespaceCharacterSet] as parameter:

NSString *foo = @" untrimmed string ";
NSString *trimmed = [foo stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

NSCharacterSet whitespaceCharacterSet example.
- (NSString *)stringByTrimmingLeadingWhitespace {
    return [self stringByTrimmingLeadingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}

- (NSString *)stringByTrimmingTrailingWhitespace {
    return [self stringByTrimmingTrailingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}

- (NSString *)stringByTrimmingLeadingWhitespaceAndNewline {
    return [self stringByTrimmingLeadingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

- (NSString *)stringByTrimmingTrailingWhitespaceAndNewline {
    return [self stringByTrimmingTrailingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

End of NSCharacterSet whitespaceCharacterSet example article.

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.

NSCharacterSet uppercaseLetterCharacterSet example in Objective C (iOS).


NSCharacterSet uppercaseLetterCharacterSet

Returns a character set containing the characters in the categories of Uppercase Letters and Titlecase Letters.

+ (id)uppercaseLetterCharacterSet

Return Value
A character set containing the characters in the categories of Uppercase Letters and Titlecase Letters.

Discussion of [NSCharacterSet uppercaseLetterCharacterSet]
Informally, this set is the set of all characters used as uppercase letters in alphabets that make case distinctions.

NSCharacterSet uppercaseLetterCharacterSet example.
NSString *s = @"This is a string"; 
int count=0; 
for (i = 0; i < [s length]; i++) {
    BOOL isUppercase = [[NSCharacterSet uppercaseLetterCharacterSet] characterIsMember:[s characterAtIndex:i]];
    if (isUppercase == YES)
       count++;
}

Example of [NSCharacterSet uppercaseLetterCharacterSet].
NSCharacterSet* uppercaseCharSet = [NSCharacterSet uppercaseLetterCharacterSet];
if ([theString rangeOfCharacterFromSet:uppercaseCharSet].location == NSNotFound)
  return NO;

NSCharacterSet* lowercaseCharSet = [NSCharacterSet lowercaseLetterCharacterSet];
if ([theString rangeOfCharacterFromSet:lowercaseCharSet].location == NSNotFound)
  return NO;

NSCharacterSet* digitsCharSet = [NSCharacterSet decimalDigitCharacterSet];
if ([theString rangeOfCharacterFromSet:digitsCharSet].location == NSNotFound)
  return NO;

return YES;
This method is Unicode-aware. If by "Upper case charecter" you just mean A-Z, use

NSCharacterSet* uppercaseCharSet =
    [NSCharacterSet characterSetWithRange:NSMakeRange('A', 26)];

NSCharacterSet uppercaseLetterCharacterSet example.
- (NSArray *)rangesOfUppercaseLettersInString:(NSString *)str {
    NSCharacterSet *cs = [NSCharacterSet uppercaseLetterCharacterSet];
    NSMutableArray *results = [NSMutableArray array];
    NSScanner *scanner = [NSScanner scannerWithString:str];
    while (![scanner isAtEnd]) {
        [scanner scanUpToCharactersFromSet:cs intoString:NULL]; // skip non-uppercase characters
        NSString *temp;
        NSUInteger location = [scanner scanLocation];
        if ([scanner scanCharactersFromSet:cs intoString:&temp]) {
            // found one (or more) uppercase characters
            NSRange range = NSMakeRange(location, [temp length]);
            [results addObject:[NSValue valueWithRange:range]];
        }
    }
    return results;
}

End of NSCharacterSet uppercaseLetterCharacterSet example article.

NSCharacterSet symbolCharacterSet example in Objective C (iOS).


NSCharacterSet symbolCharacterSet

Returns a character set containing the characters in the category of Symbols.

+ (id)symbolCharacterSet

Return Value
A character set containing the characters in the category of Symbols.

Discussion of [NSCharacterSet symbolCharacterSet]
These characters include, for example, the dollar sign ($) and the plus (+) sign.

NSCharacterSet symbolCharacterSet example.
NSCharacterSet* symbols = [NSCharacterSet symbolCharacterSet];
   if([symbols characterIsMember: yourCharacter]) {
        //Check Your condition here
    }
If you want to include many characters Use a combined NSCharacterset with NSMutableCharacterSet..

    NSMutableCharacterSet *space = [NSMutableCharacterSet characterSetWithCharactersInString:@" "];
    [space formUnionWithCharacterSet:[NSCharacterSet symbolCharacterSet]];
Use the space characterset to check the character

Example of [NSCharacterSet symbolCharacterSet].
test if for invalid chars:

[NSCharacterSet symbolCharacterSet]
rangeOfCharacterFromSet == YES if the array contains a char from the set
to rm them all:

id s = @"$bla++$bleb+$blub-$b";
NSCharacterSet *ch = [NSCharacterSet symbolCharacterSet]
s = [[s componentsSeparatedByCharactersInSet:ch] componentsJoinedByString:@""];
NSLog(@"%@ - %@",ch, s);

NSCharacterSet symbolCharacterSet example.
 while ([s scanCharactersFromSet:[NSCharacterSet symbolCharacterSet] intoString:&read]) { //symbolCharacterSet
        for(int idx=0;idx<read.length;idx=idx+6) //For Some Reason "6" works with + sign and Emojis...

        {

            NSString *word=[read substringFromIndex:0];  //substringWithRange:NSMakeRange(idx, 2)]; <-- I switched out the range and decided to get the WHOLE string.
            CGSize s = [word sizeWithFont:self.font];
            if(drawPoint.x + s.width > rect.size.width) {
                drawPoint = CGPointMake(0, drawPoint.y + s.height);

            }

End of NSCharacterSet symbolCharacterSet example article.

NSCharacterSet punctuationCharacterSet example in Objective C (iOS).


NSCharacterSet punctuationCharacterSet

Returns a character set containing the characters in the category of Punctuation.

+ (id)punctuationCharacterSet

Return Value
A character set containing the characters in the category of Punctuation.

Discussion of [NSCharacterSet punctuationCharacterSet]
Informally, this set is the set of all non-whitespace characters used to separate linguistic units in scripts, such as periods, dashes, parentheses, and so on.

NSCharacterSet punctuationCharacterSet example.
If you already know the characters that you want to remove.

NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:@"+-(),. "];
NSArray *arrayWithNumbers = [str componentsSeparatedByCharactersInSet:charSet];
NSString *numberStr = [arrayWithNumbers componentsJoinedByString:@""];
If you don't know the characters, you can use the different character sets available already

NSMutableCharacterSet *charSet = [NSMutableCharacterSet new];
[charSet formUnionWithCharacterSet:[NSCharacterSet whitespaceCharacterSet]];
[charSet formUnionWithCharacterSet:[NSCharacterSet punctuationCharacterSet]];
[charSet formUnionWithCharacterSet:[NSCharacterSet symbolCharacterSet]];
NSArray *arrayWithNumbers = [str componentsSeparatedByCharactersInSet:charSet];
NSString *numberStr = [arrayWithNumbers componentsJoinedByString:@""];

Example of [NSCharacterSet punctuationCharacterSet].
To check if a string has any characters belonging to a set, you simply do this:

NSString *testString = @"hello$%^";
NSRange r = [testString rangeOfCharactersFromSet:[NSCharacterSet punctuationCharacterSet]];
if (r.location != NSNotFound) {
    // the string contains a punctuation character
}
If you want to know all of the locations of the punctuation characters, just keep searching with a different input range. Something like:

NSRange searchRange = NSMakeRange(0, [testString length]);
while (searchRange.location != NSNotFound) {
    NSRange foundRange = [searchString rangeOrCharacterFromSet:[NSCharacterSet punctuationCharacterSet] options:0 range:searchRange];
    searchRange.location = foundRange.location + 1;
    searchRange.length = [testString length] - searchRange.location;
    if (foundRange.location != NSNotFound) {
        // found a character at foundRange.location
    }
}

NSCharacterSet punctuationCharacterSet example.
NSString *backgroundColorString = @"rgb(34, 34, 34)";

NSScanner *scanner = [NSScanner scannerWithString:backgroundColorString];
NSString *junk, *red, *green, *blue;
[scanner scanUpToCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet] intoString:&junk];
[scanner scanUpToCharactersFromSet:[NSCharacterSet punctuationCharacterSet] intoString:&red];
[scanner scanUpToCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet] intoString:&junk];
[scanner scanUpToCharactersFromSet:[NSCharacterSet punctuationCharacterSet] intoString:&blue];
[scanner scanUpToCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet] intoString:&junk];
[scanner scanUpToCharactersFromSet:[NSCharacterSet punctuationCharacterSet] intoString:&green];

UIColor *backgroundColor = [UIColor colorWithRed:red.intValue/255.0 green:green.intValue/255.0 blue:blue.intValue/255.0 alpha:1.0];

End of NSCharacterSet punctuationCharacterSet example article.

NSCharacterSet newlineCharacterSet example in Objective C (iOS).


NSCharacterSet newlineCharacterSet

Returns a character set containing the newline characters.

+ (id)newlineCharacterSet

Return Value of [NSCharacterSet newlineCharacterSet]
A character set containing the newline characters (U+000A–U+000D, U+0085).

NSCharacterSet newlineCharacterSet example.
Split the string into components and join them by space:

NSString *newString = [[myString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]] componentsJoinedByString:@" "];

Example of [NSCharacterSet newlineCharacterSet].
// grab your file
NSMutableArray *data = [[fileString componentsSeparatedByCharactersInSet: [NSCharacterSet newlineCharacterSet]] mutableCopy];
for (int i = 0; i < [data count]; i++)
{
    [data replaceObjectAtIndex: i
                    withObject: [[data objectAtIndex: i] componentsSeparatedByString: @","]];
}

NSCharacterSet newlineCharacterSet example.
NSString *address = @"129 City Road \nShoreditch \nLondon EC1V 1JB";   
address = [address stringByReplacingOccurrencesOfString:@"\n" withString:@""];
address = [address stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
This worked and i got the output like :

129 City Road Shoreditch London EC1V 1JB

End of NSCharacterSet newlineCharacterSet example article.

NSCharacterSet lowercaseLetterCharacterSet example in Objective C (iOS).


NSCharacterSet lowercaseLetterCharacterSet

Returns a character set containing the characters in the category of Lowercase Letters.

+ (id)lowercaseLetterCharacterSet

Return Value
A character set containing the characters in the category of Lowercase Letters.

Discussion of [NSCharacterSet lowercaseLetterCharacterSet]
Informally, this set is the set of all characters used as lowercase letters in alphabets that make case distinctions.

NSCharacterSet lowercaseLetterCharacterSet example.
NSCharacterSet *lowerCaseSet = [NSCharacterSet lowercaseLetterCharacterSet];

if ([myString rangeOfCharacterFromSet:lowerCaseSet].location == NSNotFound)
    NSLog(@"String is in upper case.");
else
    NSLog(@"String has invalid characters.");

Example of [NSCharacterSet lowercaseLetterCharacterSet].
NSCharacterSet  *set= [NSCharacterSet alphanumericCharacterSet];
NSString testString = @"This@9";

BOOL bResult = [testString rangeOfCharacterFromSet:[set invertedSet]].location != NSNotFound;
if(bResult)
    NSLog(@"symbol found");

set = [NSCharacterSet uppercaseLetterCharacterSet];
bResult = [password rangeOfCharacterFromSet:set].location != NSNotFound;
if(bResult)
    NSLog(@"upper case latter found");

set = [NSCharacterSet lowercaseLetterCharacterSet];
bResult = [password rangeOfCharacterFromSet:set].location != NSNotFound;
if(bResult)
    NSLog(@"lower case latter found");

set = [NSCharacterSet decimalDigitCharacterSet];
bResult = [password rangeOfCharacterFromSet:set].location != NSNotFound;
if(bResult)
    NSLog(@"digit found");

NSCharacterSet lowercaseLetterCharacterSet example.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string {

    // Check if the added string contains lowercase characters.
    // If so, those characters are replaced by uppercase characters.
    // But this has the effect of losing the editing point
    // (only when trying to edit with lowercase characters),
    // because the text of the UITextField is modified.
    // That is why we only replace the text when this is really needed.
    NSRange lowercaseCharRange;
    lowercaseCharRange = [string rangeOfCharacterFromSet:[NSCharacterSet lowercaseLetterCharacterSet]];

    if (lowercaseCharRange.location != NSNotFound) {

        textField.text = [textField.text stringByReplacingCharactersInRange:range
                                                                 withString:[string uppercaseString]];
        return NO;
    }

    return YES;
}

End of NSCharacterSet lowercaseLetterCharacterSet example article.

NSCharacterSet letterCharacterSet example in Objective C (iOS).


NSCharacterSet letterCharacterSet

Returns a character set containing the characters in the categories Letters and Marks.

+ (id)letterCharacterSet

Return Value
A character set containing the characters in the categories Letters and Marks.

Discussion of [NSCharacterSet letterCharacterSet]
Informally, this set is the set of all characters used as letters of alphabets and ideographs.

NSCharacterSet letterCharacterSet example.
NSMutableCharacterSet *mcs = [[[NSCharacterSet letterCharacterSet] invertedSet] mutableCopy];
[mcs removeCharactersInString:@"<characters you want excluded>"];

myString = [[myString componentsSeparatedByCharactersInSet:mcs] componentsJoinedByString:@""];

[mcs release];

Example of [NSCharacterSet letterCharacterSet].
@interface StringCategoryTest : GHTestCase
@end

@implementation StringCategoryTest

- (void)testStringByTrimmingLeadingCharactersInSet {
    NSCharacterSet *letterCharSet = [NSCharacterSet letterCharacterSet];
    GHAssertEqualObjects([@"zip90210zip" stringByTrimmingLeadingCharactersInSet:letterCharSet], @"90210zip", nil);
}

- (void)testStringByTrimmingLeadingWhitespaceAndNewlineCharacters {
    GHAssertEqualObjects([@"" stringByTrimmingLeadingWhitespaceAndNewlineCharacters], @"", nil);
    GHAssertEqualObjects([@"\n \n " stringByTrimmingLeadingWhitespaceAndNewlineCharacters], @"", nil);
    GHAssertEqualObjects([@"\n hello \n" stringByTrimmingLeadingWhitespaceAndNewlineCharacters], @"hello \n", nil);
}

- (void)testStringByTrimmingTrailingCharactersInSet {
    NSCharacterSet *letterCharSet = [NSCharacterSet letterCharacterSet];
    GHAssertEqualObjects([@"zip90210zip" stringByTrimmingTrailingCharactersInSet:letterCharSet], @"zip90210", nil);
}

- (void)testStringByTrimmingTrailingWhitespaceAndNewlineCharacters {
    GHAssertEqualObjects([@"" stringByTrimmingLeadingWhitespaceAndNewlineCharacters], @"", nil);
    GHAssertEqualObjects([@"\n \n " stringByTrimmingLeadingWhitespaceAndNewlineCharacters], @"", nil);
    GHAssertEqualObjects([@"\n hello \n" stringByTrimmingTrailingWhitespaceAndNewlineCharacters], @"\n hello", nil);
}

@end

NSCharacterSet letterCharacterSet example.
// The input text
NSString *text = @"BûvérÈ!@$&%^&(*^(_()-*/48";

// Defining what characters to accept
NSMutableCharacterSet *acceptedCharacters = [[NSMutableCharacterSet alloc] init];
[acceptedCharacters formUnionWithCharacterSet:[NSCharacterSet letterCharacterSet]];
[acceptedCharacters formUnionWithCharacterSet:[NSCharacterSet decimalDigitCharacterSet]];
[acceptedCharacters addCharactersInString:@" _-.!"];

// Turn accented letters into normal letters (optional)
NSData *sanitizedData = [text dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
// Corrected back-conversion from NSData to NSString
NSString *sanitizedText = [[[NSString alloc] initWithData:sanitizedData encoding:NSASCIIStringEncoding] autorelease];

// Removing unaccepted characters
NSString* output = [[sanitizedText componentsSeparatedByCharactersInSet:[acceptedCharacters invertedSet]] componentsJoinedByString:@""];

End of NSCharacterSet letterCharacterSet example article.

NSCharacterSet illegalCharacterSet example in Objective C (iOS).


NSCharacterSet illegalCharacterSet

Returns a character set containing values in the category of Non-Characters or that have not yet been defined in version 3.2 of the Unicode standard.

+ (id)illegalCharacterSet

Return Value of [NSCharacterSet illegalCharacterSet]
A character set containing values in the category of Non-Characters or that have not yet been defined in version 3.2 of the Unicode standard.

NSCharacterSet illegalCharacterSet example.
    filename = [[filename componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] componentsJoinedByString:@"" ];
    filename = [[filename componentsSeparatedByCharactersInSet:[NSCharacterSet illegalCharacterSet]] componentsJoinedByString:@"" ];
    filename = [[filename componentsSeparatedByCharactersInSet:[NSCharacterSet symbolCharacterSet]] componentsJoinedByString:@"" ];
    fileURLString = [NSTemporaryDirectory() stringByAppendingPathComponent:filename];
    fileURL = [NSURL URLWithString:fileURLString];

Example of [NSCharacterSet illegalCharacterSet].
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)string{

if (range.location>=70){
    return  NO;
}
else
{
    NSCharacterSet *unacceptedInput = nil;

    if (textView == inputTextSection || range.location>=70)  {

        NSRange uppercaseCharRange;
        uppercaseCharRange = [string rangeOfCharacterFromSet:[NSCharacterSet uppercaseLetterCharacterSet]];

        if (uppercaseCharRange.location != NSNotFound) {

            inputTextSection.text = [inputTextSection.text stringByReplacingCharactersInRange:range
                                                                                   withString:[string lowercaseString]];

            return NO;
        }

        if ([[inputTextSection.text componentsSeparatedByString:@"@"] count] > 1) {
            unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:[ALPHA_NUMERIC stringByAppendingString:@".-"]] invertedSet];

        } else {
            unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:[ALPHA_NUMERIC stringByAppendingString:@"\n .,;:<>[]!$%&'*+-/=?^_{}()~@"]] invertedSet];
        }
    }
    else {
        unacceptedInput = [[NSCharacterSet illegalCharacterSet] invertedSet];
    }

    return ([[string componentsSeparatedByCharactersInSet:unacceptedInput] count] <= 1);

    return YES;
    }
}

NSCharacterSet illegalCharacterSet example.
// Define some constants:
#define ALPHA                   @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
#define NUMERIC                 @"1234567890"
#define ALPHA_NUMERIC           ALPHA NUMERIC

// Make sure you are the text fields 'delegate', then this will get called before text gets changed.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    // This will be the character set of characters I do not want in my text field.  Then if the replacement string contains any of the characters, return NO so that the text does not change.
    NSCharacterSet *unacceptedInput = nil;

    // I have 4 types of textFields in my view, each one needs to deny a specific set of characters:
    if (textField == emailField) {
        //  Validating an email address doesnt work 100% yet, but I am working on it....  The rest work great!
        if ([[textField.text componentsSeparatedByString:@"@"] count] > 1) {
            unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:[ALPHA_NUMERIC stringByAppendingString:@".-"]] invertedSet];
        } else {
            unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:[ALPHA_NUMERIC stringByAppendingString:@".!#$%&'*+-/=?^_`{|}~@"]] invertedSet];
        }
    } else if (textField == phoneField) {
        unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:NUMERIC] invertedSet];
    } else if (textField == fNameField || textField == lNameField) {
        unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:ALPHA] invertedSet];
    } else {
        unacceptedInput = [[NSCharacterSet illegalCharacterSet] invertedSet];
    }

    // If there are any characters that I do not want in the text field, return NO.
    return ([[string componentsSeparatedByCharactersInSet:unacceptedInput] count] <= 1);
}

End of NSCharacterSet illegalCharacterSet example article.

NSCharacterSet decomposableCharacterSet example in Objective C (iOS).


NSCharacterSet decomposableCharacterSet

Returns a character set containing all individual Unicode characters that can also be represented as composed character sequences.

+ (id)decomposableCharacterSet

Return Value of [NSCharacterSet decomposableCharacterSet]
A character set containing all individual Unicode characters that can also be represented as composed character sequences (such as for letters with accents), by the definition of “standard decomposition” in version 3.2 of the Unicode character encoding standard.

Discussion of [NSCharacterSet decomposableCharacterSet]
These characters include compatibility characters as well as pre-composed characters.

Note: This character set doesn’t currently include the Hangul characters defined in version 2.0 of the Unicode standard.

NSCharacterSet decomposableCharacterSet example.
NSString *inputString = @"VästerÃ¥s  ;; Swed   en    ";

NSLog(@"Input String %@",inputString);

inputString = [inputString lowercaseString]; // Lower case

inputString = [inputString stringByReplacingOccurrencesOfString:@" " withString:@""]; //Whitespace

inputString = [[inputString componentsSeparatedByCharactersInSet:[[NSCharacterSet letterCharacterSet] invertedSet]] componentsJoinedByString:@""]; //Punctuation

inputString = [[inputString componentsSeparatedByCharactersInSet:[NSCharacterSet decomposableCharacterSet]] componentsJoinedByString:@""]; // non-english characters

End of NSCharacterSet decomposableCharacterSet example article.

NSCharacterSet decimalDigitCharacterSet example in Objective C (iOS).


NSCharacterSet decimalDigitCharacterSet

Returns a character set containing the characters in the category of Decimal Numbers.

+ (id)decimalDigitCharacterSet

Return Value
A character set containing the characters in the category of Decimal Numbers.

Discussion of [NSCharacterSet decimalDigitCharacterSet]
Informally, this set is the set of all characters used to represent the decimal values 0 through 9. These characters include, for example, the decimal digits of the Indic scripts and Arabic.

NSCharacterSet decimalDigitCharacterSet example.
NSString *newString = [[origString componentsSeparatedByCharactersInSet:
             [[NSCharacterSet decimalDigitCharacterSet] invertedSet]]
             componentsJoinedByString:@""];

Example of [NSCharacterSet decimalDigitCharacterSet].
Here's one way that doesn't rely on the limited precision of attempting to parse the string as a number:

NSCharacterSet* notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
if ([newString rangeOfCharacterFromSet:notDigits].location == NSNotFound)
{
    // newString consists only of the digits 0 through 9
}

NSCharacterSet decimalDigitCharacterSet example.
 NSString *str = @"001234852ACDSB";
    NSScanner *scanner = [NSScanner scannerWithString:str];

    // set it to skip non-numeric characters
    [scanner setCharactersToBeSkipped:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];

    int i;
    while ([scanner scanInt:&i])
    {
        NSLog(@"Found int: %d",i);    //001234852
    }

    // reset the scanner to skip numeric characters
    [scanner setScanLocation:0];
    [scanner setCharactersToBeSkipped:[NSCharacterSet decimalDigitCharacterSet]];

    NSString *resultString;
    while ([scanner scanUpToCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet] intoString:&resultString])
    {
        NSLog(@"Found string: %@",resultString);    //ACDSB
    }

End of NSCharacterSet decimalDigitCharacterSet example article.

NSCharacterSet characterSetWithRange example in Objective C (iOS).


NSCharacterSet characterSetWithRange

Returns a character set containing characters with Unicode values in a given range.

+ (id)characterSetWithRange:(NSRange)aRange

Parameters
aRange
A range of Unicode values.
aRange.location is the value of the first character to return; aRange.location + aRange.length– 1 is the value of the last.

Return Value
A character set containing characters whose Unicode values are given by aRange. If aRange.length is 0, returns an empty character set.

Discussion of [NSCharacterSet characterSetWithRange]
This code excerpt creates a character set object containing the lowercase English alphabetic characters:

NSCharacterSet characterSetWithRange example.
NSRange lcEnglishRange;
NSCharacterSet *lcEnglishLetters;

lcEnglishRange.location = (unsigned int)'a';
lcEnglishRange.length = 26;
lcEnglishLetters = [NSCharacterSet characterSetWithRange:lcEnglishRange];

Example of [NSCharacterSet characterSetWithRange].
You can make your character sets as follows for arbitrary ranges of ASCII characters:

NSCharacterSet *a_to_d_Set = [NSCharacterSet characterSetWithRange:NSMakeRange('a', 'd'-'a' + 1)];
NSCharacterSet *e_to_l_Set = [NSCharacterSet characterSetWithRange:NSMakeRange('e', 'l'-'e' + 1)];
Of course, you could equivalently write:

NSCharacterSet *a_to_d_Set = [NSCharacterSet characterSetWithRange:NSMakeRange('a', 4)];

NSCharacterSet characterSetWithRange example.
This method is Unicode-aware. If by "Upper case charecter" you just mean A-Z, use

NSCharacterSet* uppercaseCharSet =
    [NSCharacterSet characterSetWithRange:NSMakeRange('A', 26)];

End of NSCharacterSet characterSetWithRange example article.

NSCharacterSet characterSetWithCharactersInString example in Objective C (iOS).


NSCharacterSet characterSetWithCharactersInString

Returns a character set containing the characters in a given string.

+ (id)characterSetWithCharactersInString:(NSString *)aString

Parameters
aString
A string containing characters for the new character set.

Return Value of [NSCharacterSet characterSetWithCharactersInString]
A character set containing the characters in aString. Returns an empty character set if aString is empty.

NSCharacterSet characterSetWithCharactersInString example.
You can create your own character set:

NSCharacterSet *s = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_"];
Once you have that, you invert it to everything that's not in your original string:

s = [s invertedSet];
And you can then use a string method to find if your string contains anything in the inverted set:

NSRange r = [string rangeOfCharacterFromSet:s];
if (r.location != NSNotFound) {
  NSLog(@"the string contains illegal characters");
}

Example of [NSCharacterSet characterSetWithCharactersInString].
NSString *originalString = @"(123) 123123 abc";
NSMutableString *strippedString = [NSMutableString
        stringWithCapacity:originalString.length];

NSScanner *scanner = [NSScanner scannerWithString:originalString];
NSCharacterSet *numbers = [NSCharacterSet
        characterSetWithCharactersInString:@"0123456789"];

while ([scanner isAtEnd] == NO) {
  NSString *buffer;
  if ([scanner scanCharactersFromSet:numbers intoString:&buffer]) {
    [strippedString appendString:buffer];

  } else {
    [scanner setScanLocation:([scanner scanLocation] + 1)];
  }
}

NSLog(@"%@", strippedString); // "123123123"

NSCharacterSet characterSetWithCharactersInString example.
NSString* string = @"ABCCDEDRFFED";
NSCharacterSet* characters = [NSCharacterSet characterSetWithCharactersInString:@"ABC"];
NSUInteger characterCount;

NSUInteger i;
for (i = 0; i < [yourString length]; i++) {
  unichar character = [yourString characterAtIndex:i];
  if ([characters characterIsMember:character]) characterCount++;
}

NSLog(@"Total characters = %d", characterCount);

End of NSCharacterSet characterSetWithCharactersInString example article.

NSCharacterSet capitalizedLetterCharacterSet example in Objective C (iOS).


NSCharacterSet capitalizedLetterCharacterSet

Returns a character set containing the characters in the category of Titlecase Letters.

+ (id)capitalizedLetterCharacterSet

Return Value of [NSCharacterSet capitalizedLetterCharacterSet]
A character set containing the characters in the category of Titlecase Letters.

NSCharacterSet capitalizedLetterCharacterSet example.
unichar aChar = [myString characterAtIndex: someIndex];

NSCharacterSet* theCaps [NSCharacterSet capitalizedLetterCharacterSet];
if ([theCaps characterIsMember: aChar])
{
  //Character is an upper case character
}
else
{
  //Character is not an upper case character.
}

Example of [NSCharacterSet capitalizedLetterCharacterSet].

unichar testChar = [inputString characterAtIndex:i+1];
NSCharacterSet *theCaps = [NSCharacterSet capitalizedLetterCharacterSet];
if ([theCaps characterIsMember:testChar]) {
    NSLog(@\"Uppercase\");
}
else {
    NSLog(@\"Lowercase\");
}

NSCharacterSet capitalizedLetterCharacterSet example.
NSCharacterSet *letters = [NSCharacterSet capitalizedLetterCharacterSet];
NSCharacterSet *inStringSet = [NSCharacterSet characterSetWithCharactersInString:@\"ABCD\"];
valid = [letters isSupersetOfSet:inStringSet];

End of NSCharacterSet capitalizedLetterCharacterSet example article.

NSCharacterSet alphanumericCharacterSet example in Objective C (iOS).


NSCharacterSet alphanumericCharacterSet

Returns a character set containing the characters in the categories Letters, Marks, and Numbers.

+ (id)alphanumericCharacterSet

Return Value
A character set containing the characters in the categories Letters, Marks, and Numbers.

Discussion of [NSCharacterSet alphanumericCharacterSet]
Informally, this set is the set of all characters used as basic units of alphabets, syllabaries, ideographs, and digits.

NSCharacterSet alphanumericCharacterSet example.
NSMutableCharacterSet *_alnum = [NSMutableCharacterSet characterSetWithCharactersInString@"_"];
[_alnum formUnionWithCharacterSet:[NSCharacterSet alphanumericCharacterSet]];

Example of [NSCharacterSet alphanumericCharacterSet].
NSCharacterSet *charactersToRemove =
[[ NSCharacterSet alphanumericCharacterSet ] invertedSet ];

NSString *trimmedReplacement =
[[ someString componentsSeparatedByCharactersInSet:charactersToRemove ]
 componentsJoinedByString:@"" ];

NSCharacterSet alphanumericCharacterSet example.
@implementation NSString (alphaOnly)

- (BOOL) isAlphaNumeric
   {
    NSCharacterSet *unwantedCharacters =
       [[NSCharacterSet alphanumericCharacterSet] invertedSet];

    return ([self rangeOfCharacterFromSet:unwantedCharacters].location == NSNotFound) ? YES : NO;
    }

@end

End of NSCharacterSet alphanumericCharacterSet example article.

NSComparisonPredicate NSInPredicateOperatorType example in Objective C (iOS).


NSComparisonPredicate NSInPredicateOperatorType

NSPredicateOperatorType
Defines the type of comparison for NSComparisonPredicate.

enum {
NSLessThanPredicateOperatorType = 0,
NSLessThanOrEqualToPredicateOperatorType,
NSGreaterThanPredicateOperatorType,
NSGreaterThanOrEqualToPredicateOperatorType,
NSEqualToPredicateOperatorType,
NSNotEqualToPredicateOperatorType,
NSMatchesPredicateOperatorType,
NSLikePredicateOperatorType,
NSBeginsWithPredicateOperatorType,
NSEndsWithPredicateOperatorType,
NSInPredicateOperatorType,
NSCustomSelectorPredicateOperatorType,
NSContainsPredicateOperatorType,
NSBetweenPredicateOperatorType
};
typedef NSUInteger NSPredicateOperatorType;

Constants
NSLessThanPredicateOperatorType
A less-than predicate.
NSLessThanOrEqualToPredicateOperatorType
A less-than-or-equal-to predicate.
NSGreaterThanPredicateOperatorType
A greater-than predicate.
NSGreaterThanOrEqualToPredicateOperatorType
A greater-than-or-equal-to predicate.
NSEqualToPredicateOperatorType
An equal-to predicate.
NSNotEqualToPredicateOperatorType
A not-equal-to predicate.
NSMatchesPredicateOperatorType
A full regular expression matching predicate.
NSLikePredicateOperatorType
A simple subset of the MATCHES predicate, similar in behavior to SQL LIKE.
NSBeginsWithPredicateOperatorType
A begins-with predicate.
NSEndsWithPredicateOperatorType
An ends-with predicate.
NSInPredicateOperatorType
A predicate to determine if the left hand side is in the right hand side.
For strings, returns YES if the left hand side is a substring of the right hand side . For collections, returns YES if the left hand side is in the right hand side .
NSCustomSelectorPredicateOperatorType
A predicate that uses a custom selector that takes a single argument and returns a BOOL value.
The selector is invoked on the left hand side with the right hand side as the argument.
NSContainsPredicateOperatorType
A predicate to determine if the left hand side contains the right hand side.
Returns YES if [lhs contains rhs]; the left hand side must be an NSExpression object that evaluates to a collection
NSBetweenPredicateOperatorType
A predicate to determine if the right hand side lies at or between bounds specified by the left hand side.
Returns YES if [lhs between rhs]; the right hand side must be an array in which the first element sets the lower bound and the second element the upper, inclusive. Comparison is performed using compare: or the class-appropriate equivalent.

NSComparisonPredicate NSInPredicateOperatorType example.
First, I get all the EntityC that satisfy the condition EntityC.name equal to 'SomeName'

NSPredicate *p = [NSPredicate predicateWithFormat:@"name like %@", @"SomeName];
...

NSArray *res = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
Then I get an array of EntityB from above query

NSArray *parentBs = [res valueForKeyPath:@"@distinctUnionOfObjects.parent"];
Than get array of EntityB that satisfy the condition EntityB.EntitiesC.name equal to 'SomeName':

NSExpression *leftExpression = [NSExpression expressionForEvaluatedObject];
NSExpression *rightExpression = [NSExpression expressionForConstantValue:parentBs];

NSPredicate *p = [NSComparisonPredicate predicateWithLeftExpression:leftExpression rightExpression: rightExpression modifier:NSDirectPredicateModifier type:NSInPredicateOperatorType options:0];

Example of [NSComparisonPredicate NSInPredicateOperatorType].
fetchRequest.entity = [NSEntityDescription entityForName:@"myRecord" inManagedObjectContext:self.managedObjectContext]];

NSArray *shipTypes = [NSArray arrayWithObjects:[NSNumber numberWithInt:70],
                                        [NSNumber numberWithInt:71],
                                        [NSNumber numberWithInt:72],
                                        [NSNumber numberWithInt:73],
                                        [NSNumber numberWithInt:74],
                                         nil];
fetchRequest.predicate = [NSComparisonPredicate predicateWithLeftExpression:[NSExpression expressionForKeyPath:@"type"] rightExpression:[NSExpression expressionForConstantValue:shipTypes] modifier:NSDirectPredicateModifier type:NSInPredicateOperatorType options:0];

theRecords = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];

End of NSComparisonPredicate NSInPredicateOperatorType example article.

NSComparisonPredicate NSContainsPredicateOperatorType example in Objective C (iOS).


NSComparisonPredicate NSContainsPredicateOperatorType

NSPredicateOperatorType
Defines the type of comparison for NSComparisonPredicate.

enum {
NSLessThanPredicateOperatorType = 0,
NSLessThanOrEqualToPredicateOperatorType,
NSGreaterThanPredicateOperatorType,
NSGreaterThanOrEqualToPredicateOperatorType,
NSEqualToPredicateOperatorType,
NSNotEqualToPredicateOperatorType,
NSMatchesPredicateOperatorType,
NSLikePredicateOperatorType,
NSBeginsWithPredicateOperatorType,
NSEndsWithPredicateOperatorType,
NSInPredicateOperatorType,
NSCustomSelectorPredicateOperatorType,
NSContainsPredicateOperatorType,
NSBetweenPredicateOperatorType
};
typedef NSUInteger NSPredicateOperatorType;

Constants
NSLessThanPredicateOperatorType
A less-than predicate.
NSLessThanOrEqualToPredicateOperatorType
A less-than-or-equal-to predicate.
NSGreaterThanPredicateOperatorType
A greater-than predicate.
NSGreaterThanOrEqualToPredicateOperatorType
A greater-than-or-equal-to predicate.
NSEqualToPredicateOperatorType
An equal-to predicate.
NSNotEqualToPredicateOperatorType
A not-equal-to predicate.
NSMatchesPredicateOperatorType
A full regular expression matching predicate.
NSLikePredicateOperatorType
A simple subset of the MATCHES predicate, similar in behavior to SQL LIKE.
NSBeginsWithPredicateOperatorType
A begins-with predicate.
NSEndsWithPredicateOperatorType
An ends-with predicate.
NSInPredicateOperatorType
A predicate to determine if the left hand side is in the right hand side.
For strings, returns YES if the left hand side is a substring of the right hand side . For collections, returns YES if the left hand side is in the right hand side .
NSCustomSelectorPredicateOperatorType
A predicate that uses a custom selector that takes a single argument and returns a BOOL value.
The selector is invoked on the left hand side with the right hand side as the argument.
NSContainsPredicateOperatorType
A predicate to determine if the left hand side contains the right hand side.
Returns YES if [lhs contains rhs]; the left hand side must be an NSExpression object that evaluates to a collection
NSBetweenPredicateOperatorType
A predicate to determine if the right hand side lies at or between bounds specified by the left hand side.
Returns YES if [lhs between rhs]; the right hand side must be an array in which the first element sets the lower bound and the second element the upper, inclusive. Comparison is performed using compare: or the class-appropriate equivalent.

NSComparisonPredicate NSContainsPredicateOperatorType example.
NSExpression *nameExpression = [NSExpression expressionForKeyPath:@"name"];
NSArray *operators = [NSArray arrayWithObjects:
      [NSNumber numberWithInt: NSEqualToPredicateOperatorType],
      [NSNumber numberWithInt:NSNotEqualToPredicateOperatorType],
      [NSNumber numberWithInt:NSLikePredicateOperatorType],
      [NSNumber numberWithInt:NSBeginsWithPredicateOperatorType],
      [NSNumber numberWithInt:NSEndsWithPredicateOperatorType],
      [NSNumber numberWithInt:NSContainsPredicateOperatorType],
      nil];

NSUInteger options = (NSCaseInsensitivePredicateOption |
                      NSDiacriticInsensitivePredicateOption);

NSPredicateEditorRowTemplate *template = [[NSPredicateEditorRowTemplate alloc]
      initWithLeftExpressions:[NSArray arrayWithObject:nameExpression]
      rightExpressionAttributeType:NSStringAttributeType
      modifier:NSDirectPredicateModifier
      operators:operators
      options:options];

Example of [NSComparisonPredicate NSContainsPredicateOperatorType].
NSExpression * leftExpression = [NSExpression expressionForKeyPath:@"name"];
NSExpression * rightExpression = [NSExpression expressionForConstantValue:@"Hello!"];

NSComparisonPredicate * predicate = [NSComparisonPredicate predicateWithLeftExpression:leftExpression
                                                                       rightExpression:rightExpression
                                                                              modifier:NSDirectPredicateModifier
                                                                                  type:NSContainsPredicateOperatorType
                                                                               options:(NSCaseInsensitivePredicateOption | NSDiacriticInsensitivePredicateOption)];

End of NSComparisonPredicate NSContainsPredicateOperatorType example article.

NSComparisonPredicate NSEndsWithPredicateOperatorType example in Objective C (iOS).


NSComparisonPredicate NSEndsWithPredicateOperatorType

NSPredicateOperatorType
Defines the type of comparison for NSComparisonPredicate.

enum {
NSLessThanPredicateOperatorType = 0,
NSLessThanOrEqualToPredicateOperatorType,
NSGreaterThanPredicateOperatorType,
NSGreaterThanOrEqualToPredicateOperatorType,
NSEqualToPredicateOperatorType,
NSNotEqualToPredicateOperatorType,
NSMatchesPredicateOperatorType,
NSLikePredicateOperatorType,
NSBeginsWithPredicateOperatorType,
NSEndsWithPredicateOperatorType,
NSInPredicateOperatorType,
NSCustomSelectorPredicateOperatorType,
NSContainsPredicateOperatorType,
NSBetweenPredicateOperatorType
};
typedef NSUInteger NSPredicateOperatorType;

Constants
NSLessThanPredicateOperatorType
A less-than predicate.
NSLessThanOrEqualToPredicateOperatorType
A less-than-or-equal-to predicate.
NSGreaterThanPredicateOperatorType
A greater-than predicate.
NSGreaterThanOrEqualToPredicateOperatorType
A greater-than-or-equal-to predicate.
NSEqualToPredicateOperatorType
An equal-to predicate.
NSNotEqualToPredicateOperatorType
A not-equal-to predicate.
NSMatchesPredicateOperatorType
A full regular expression matching predicate.
NSLikePredicateOperatorType
A simple subset of the MATCHES predicate, similar in behavior to SQL LIKE.
NSBeginsWithPredicateOperatorType
A begins-with predicate.
NSEndsWithPredicateOperatorType
An ends-with predicate.
NSInPredicateOperatorType
A predicate to determine if the left hand side is in the right hand side.
For strings, returns YES if the left hand side is a substring of the right hand side . For collections, returns YES if the left hand side is in the right hand side .
NSCustomSelectorPredicateOperatorType
A predicate that uses a custom selector that takes a single argument and returns a BOOL value.
The selector is invoked on the left hand side with the right hand side as the argument.
NSContainsPredicateOperatorType
A predicate to determine if the left hand side contains the right hand side.
Returns YES if [lhs contains rhs]; the left hand side must be an NSExpression object that evaluates to a collection
NSBetweenPredicateOperatorType
A predicate to determine if the right hand side lies at or between bounds specified by the left hand side.
Returns YES if [lhs between rhs]; the right hand side must be an array in which the first element sets the lower bound and the second element the upper, inclusive. Comparison is performed using compare: or the class-appropriate equivalent.

NSComparisonPredicate NSEndsWithPredicateOperatorType example.
NSExpression *nameExpression = [NSExpression expressionForKeyPath:@"name"];
NSArray *operators = [NSArray arrayWithObjects:
      [NSNumber numberWithInt: NSEqualToPredicateOperatorType],
      [NSNumber numberWithInt:NSNotEqualToPredicateOperatorType],
      [NSNumber numberWithInt:NSLikePredicateOperatorType],
      [NSNumber numberWithInt:NSBeginsWithPredicateOperatorType],
      [NSNumber numberWithInt:NSEndsWithPredicateOperatorType],
      [NSNumber numberWithInt:NSContainsPredicateOperatorType],
      nil];

NSUInteger options = (NSCaseInsensitivePredicateOption |
                      NSDiacriticInsensitivePredicateOption);

NSPredicateEditorRowTemplate *template = [[NSPredicateEditorRowTemplate alloc]
      initWithLeftExpressions:[NSArray arrayWithObject:nameExpression]
      rightExpressionAttributeType:NSStringAttributeType
      modifier:NSDirectPredicateModifier
      operators:operators
      options:options];

End of NSComparisonPredicate NSEndsWithPredicateOperatorType example article.

NSComparisonPredicate NSBeginsWithPredicateOperatorType example in Objective C (iOS).


NSComparisonPredicate NSBeginsWithPredicateOperatorType

NSPredicateOperatorType
Defines the type of comparison for NSComparisonPredicate.

enum {
NSLessThanPredicateOperatorType = 0,
NSLessThanOrEqualToPredicateOperatorType,
NSGreaterThanPredicateOperatorType,
NSGreaterThanOrEqualToPredicateOperatorType,
NSEqualToPredicateOperatorType,
NSNotEqualToPredicateOperatorType,
NSMatchesPredicateOperatorType,
NSLikePredicateOperatorType,
NSBeginsWithPredicateOperatorType,
NSEndsWithPredicateOperatorType,
NSInPredicateOperatorType,
NSCustomSelectorPredicateOperatorType,
NSContainsPredicateOperatorType,
NSBetweenPredicateOperatorType
};
typedef NSUInteger NSPredicateOperatorType;

Constants
NSLessThanPredicateOperatorType
A less-than predicate.
NSLessThanOrEqualToPredicateOperatorType
A less-than-or-equal-to predicate.
NSGreaterThanPredicateOperatorType
A greater-than predicate.
NSGreaterThanOrEqualToPredicateOperatorType
A greater-than-or-equal-to predicate.
NSEqualToPredicateOperatorType
An equal-to predicate.
NSNotEqualToPredicateOperatorType
A not-equal-to predicate.
NSMatchesPredicateOperatorType
A full regular expression matching predicate.
NSLikePredicateOperatorType
A simple subset of the MATCHES predicate, similar in behavior to SQL LIKE.
NSBeginsWithPredicateOperatorType
A begins-with predicate.
NSEndsWithPredicateOperatorType
An ends-with predicate.
NSInPredicateOperatorType
A predicate to determine if the left hand side is in the right hand side.
For strings, returns YES if the left hand side is a substring of the right hand side . For collections, returns YES if the left hand side is in the right hand side .
NSCustomSelectorPredicateOperatorType
A predicate that uses a custom selector that takes a single argument and returns a BOOL value.
The selector is invoked on the left hand side with the right hand side as the argument.
NSContainsPredicateOperatorType
A predicate to determine if the left hand side contains the right hand side.
Returns YES if [lhs contains rhs]; the left hand side must be an NSExpression object that evaluates to a collection
NSBetweenPredicateOperatorType
A predicate to determine if the right hand side lies at or between bounds specified by the left hand side.
Returns YES if [lhs between rhs]; the right hand side must be an array in which the first element sets the lower bound and the second element the upper, inclusive. Comparison is performed using compare: or the class-appropriate equivalent.

NSComparisonPredicate NSBeginsWithPredicateOperatorType example.
NSExpression *nameExpression = [NSExpression expressionForKeyPath:@"name"];
NSArray *operators = [NSArray arrayWithObjects:
      [NSNumber numberWithInt: NSEqualToPredicateOperatorType],
      [NSNumber numberWithInt:NSNotEqualToPredicateOperatorType],
      [NSNumber numberWithInt:NSLikePredicateOperatorType],
      [NSNumber numberWithInt:NSBeginsWithPredicateOperatorType],
      [NSNumber numberWithInt:NSEndsWithPredicateOperatorType],
      [NSNumber numberWithInt:NSContainsPredicateOperatorType],
      nil];

NSUInteger options = (NSCaseInsensitivePredicateOption |
                      NSDiacriticInsensitivePredicateOption);

NSPredicateEditorRowTemplate *template = [[NSPredicateEditorRowTemplate alloc]
      initWithLeftExpressions:[NSArray arrayWithObject:nameExpression]
      rightExpressionAttributeType:NSStringAttributeType
      modifier:NSDirectPredicateModifier
      operators:operators
      options:options];

End of NSComparisonPredicate NSBeginsWithPredicateOperatorType example article.