Objective c: Check if integer/int/number

前端 未结 6 2225
不知归路
不知归路 2021-02-13 02:25

In objective c, how can i check if a string/NSNumber is an integer or int

6条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-13 03:12

    For NSString, if you use intValue/integerValue, there are certain cases which are not handled as it takes into consideration only the beginning the string.

    For example @"bl3h" was not considered an integer but @" 3h" gave an output of 3

    My solution for NSString:

    Use :

    NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:strName];
    
    NSCharacterSet *numSet = [NSCharacterSet decimalDigitCharacterSet];
    
    if([numSet isSupersetOfSet: charSet])
    {
         // It is an integer (or it contains only digits)
    }
    

提交回复
热议问题