Search code examples
iosobjective-cnscharacterset

What happens when rangeOfCharacterFromSet is called?


What this following code mean, I know this is to avoid typing characters other than numbers in a TextField. But what is actually happening behind this function rangeOfCharacterFromSet . What it will return.

if ([string rangeOfCharacterFromSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]].location != NSNotFound)
        return NO;

In documentation it said

Finds and returns the range in the receiver of the first character from a given character set. The range in the receiver of the first character found from aSet. Returns a range of {NSNotFound, 0} if none of the characters in aSet are found

I can't even understand what is receiver And why NSNotFound is used here. And what is that aSet

Please explain me with some example for better understanding (Like what will happen when i press a character other than numbers)


Solution

  • - (void)test {
    NSString *str = @"input content";
    NSCharacterSet *characterSet = [NSCharacterSet decimalDigitCharacterSet];
    NSRange range = [str rangeOfCharacterFromSet:characterSet];
    NSLog(@"location:%ld, length:%ld", range.location, range.length);
    // range.location is 9223372036854775807, in fact it is a NSNotFound which means not exists, range.length is 0
    
    str = @"input 1";
    range = [str rangeOfCharacterFromSet:characterSet];
    NSLog(@"location:%ld, length:%ld", range.location, range.length);
    // range.location is 6, range.length is 1
    
    str = @"input 123";
    range = [str rangeOfCharacterFromSet:characterSet];
    NSLog(@"location:%ld, length:%ld", range.location, range.length);
    // range.location is 6, range.length is 1
    
    str = @"123 input 123";
    range = [str rangeOfCharacterFromSet:characterSet];
    NSLog(@"location:%ld, length:%ld", range.location, range.length);
    // range.location is 0, range.length is 1
    }
    

    In the test, str is the receiver, when you call a method, who call who is reciever: [receiver callTheMethod]. Abount NSCharacterSet, I think the document explains clearly:

    An NSCharacterSet object represents a set of Unicode-compliant characters. NSString and NSScanner objects use NSCharacterSet objects to group characters together for searching operations, so that they can find any of a particular set of characters during a search. The cluster’s two public classes, NSCharacterSet and NSMutableCharacterSet, declare the programmatic interface for static and dynamic character sets, respectively.

    NSRange is the result of [str rangeOfCharacterFromSet:characterSet], it is a struct, range.location is the first index in str which is included in characterSet, it is a NSInteger type, when the str not exits a the content of characterSet it will be a very big integer, and it means NSNotFound. range.length means as the words, at here, it always is 1 unless range.location is NSNotFound.

    Hope it helps.