Objective-C: Find numbers in string

Here’s an NSScanner based solution: // Input NSString *originalString = @”This is my string. #1234″; // Intermediate NSString *numberString; NSScanner *scanner = [NSScanner scannerWithString:originalString]; NSCharacterSet *numbers = [NSCharacterSet characterSetWithCharactersInString:@”0123456789″]; // Throw away characters before the first number. [scanner scanUpToCharactersFromSet:numbers intoString:NULL]; // Collect numbers. [scanner scanCharactersFromSet:numbers intoString:&numberString]; // Result. int number = [numberString integerValue]; (Some of … Read more

get type of NSNumber

I recommend using the -[NSNumber objCType] method. It allows you to do: NSNumber * n = [NSNumber numberWithBool:YES]; if (strcmp([n objCType], @encode(BOOL)) == 0) { NSLog(@”this is a bool”); } else if (strcmp([n objCType], @encode(int)) == 0) { NSLog(@”this is an int”); } For more information on type encodings, check out the Objective-C Runtime Reference.

What’s the difference between NSNumber and NSInteger?

NSNumber is a class, not a primitive, and is used when you need to put raw numbers into dictionaries, arrays, or otherwise encapsulate them. NSInteger, NSUInteger, CGFloat, etc are simple types and correspond (on 32-bt systems like the iPhone) to int, unsigned int and float. As a general rule, if you need to store a … Read more

String to NSNumber in Swift

Swift 3.0 NSNumber(integer:myInteger) has changed to NSNumber(value:myInteger) let someString = “42222222222” if let myInteger = Int(someString) { let myNumber = NSNumber(value:myInteger) } Swift 2.0 Use the Int() initialiser like this. let someString = “42222222222” if let myInteger = Int(someString) { let myNumber = NSNumber(integer:myInteger) print(myNumber) } else { print(“‘\(someString)’ did not convert to an Int”) … Read more

Working with NSNumber & Integer values in Swift 3

Before Swift 3, many types were automatically “bridged” to an instance of some NSObject subclass where necessary, such as String to NSString, or Int, Float, … to NSNumber. As of Swift 3 you have to make that conversion explicit: var currentIndex = 0 for item in self.selectedFolder.arrayOfTasks { item.index = currentIndex as NSNumber // <– … Read more

tech