Split an NSString to access one particular piece

NSArray* foo = [@”10/04/2011″ componentsSeparatedByString: @”https://stackoverflow.com/”]; NSString* firstBit = [foo objectAtIndex: 0]; Update 7/3/2018: Now that the question has acquired a Swift tag, I should add the Swift way of doing this. It’s pretty much as simple: let substrings = “10/04/2011”.split(separator: “https://stackoverflow.com/”) let firstBit = substrings[0] Although note that it gives you an array of … Read more

How do I deserialize a JSON string into an NSDictionary? (For iOS 5+)

It looks like you are passing an NSString parameter where you should be passing an NSData parameter: NSError *jsonError; NSData *objectData = [@”{\”2\”:\”3\”}” dataUsingEncoding:NSUTF8StringEncoding]; NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData options:NSJSONReadingMutableContainers error:&jsonError];

Remove all but numbers from NSString

Old question, but how about: NSString *newString = [[origString componentsSeparatedByCharactersInSet: [[NSCharacterSet decimalDigitCharacterSet] invertedSet]] componentsJoinedByString:@””]; It explodes the source string on the set of non-digits, then reassembles them using an empty string separator. Not as efficient as picking through characters, but much more compact in code.

Creating NSData from NSString in Swift

In Swift 3 let data = string.data(using: .utf8) In Swift 2 (or if you already have a NSString instance) let data = string.dataUsingEncoding(NSUTF8StringEncoding) In Swift 1 (or if you have a swift String): let data = (string as NSString).dataUsingEncoding(NSUTF8StringEncoding) Also note that data is an Optional<NSData> (since the conversion might fail), so you’ll need to … Read more

How can I convert my device token (NSData) into an NSString?

If anyone is looking for a way to do this in Swift: Swift 3 introduces the Data type, with value semantics. To convert the deviceToken to a String, you can do as follows: func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { let token = deviceToken.map { String(format: “%02.2hhx”, $0) }.joined() print(token) } Old answer using … Read more

How do I URL encode a string

Unfortunately, stringByAddingPercentEscapesUsingEncoding doesn’t always work 100%. It encodes non-URL characters but leaves the reserved characters (like slash / and ampersand &) alone. Apparently this is a bug that Apple is aware of, but since they have not fixed it yet, I have been using this category to url-encode a string: @implementation NSString (NSString_Extended) – (NSString … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)