Define a category in NSString (put this on top of any of the source code modules or in a new pair of .m / .h files, @interface goes into .h, @implementation in .m):
@interface NSString (NSStringWithOctal) -(int)octalIntValue; @end @implementation NSString (NSStringWithOctal) -(int)octalIntValue { int iResult = 0, iBase = 1; char c; for(int i=(int)[self length]-1; i>=0; i--) { c = [self characterAtIndex:i]; if((c<'0')||(c>'7')) return 0; iResult += (c - '0') * iBase; iBase *= 8; } return iResult; } @end
Use it like this:
NSString *s = @"77"; int i = [s octalIntValue]; NSLog(@"%d", i);
The method returns an integer representing the octal value in the string. It returns 0 if the string is not an octal number. Leading zeros are allowed, but not required.
source share