NSRange to Range

As of Swift 4 (Xcode 9), the Swift standard library provides methods to convert between Swift string ranges (Range<String.Index>) and NSString ranges (NSRange). Example: let str = “a👿b🇩🇪c” let r1 = str.range(of: “🇩🇪”)! // String range to NSRange: let n1 = NSRange(r1, in: str) print((str as NSString).substring(with: n1)) // 🇩🇪 // NSRange back to String … Read more

Convert UTF-8 encoded NSData to NSString

If the data is not null-terminated, you should use -initWithData:encoding: NSString* newStr = [[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding]; If the data is null-terminated, you should instead use -stringWithUTF8String: to avoid the extra \0 at the end. NSString* newStr = [NSString stringWithUTF8String:[theData bytes]]; (Note that if the input is not properly UTF-8-encoded, you will get nil.) Swift … 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

Shortcuts in Objective-C to concatenate NSStrings

An option: [NSString stringWithFormat:@”%@/%@/%@”, one, two, three]; Another option: I’m guessing you’re not happy with multiple appends (a+b+c+d), in which case you could do: NSLog(@”%@”, [Util append:one, @” “, two, nil]); // “one two” NSLog(@”%@”, [Util append:three, @”https://stackoverflow.com/”, two, @”https://stackoverflow.com/”, one, nil]); // three/two/one using something like + (NSString *) append:(id) first, … { NSString … Read more

Constants in Objective-C

You should create a header file like: // Constants.h FOUNDATION_EXPORT NSString *const MyFirstConstant; FOUNDATION_EXPORT NSString *const MySecondConstant; //etc. (You can use extern instead of FOUNDATION_EXPORT if your code will not be used in mixed C/C++ environments or on other platforms.) You can include this file in each file that uses the constants or in the … Read more