I recently was working on a project where I wanted to display an integer value as a binary string in Objective-C. Once I wrote what I thought were two decent implementations, I was curious to see how another developer would approach the same problem.
I asked Nick Lockwood if he would be up for coding up something similar. Bear in mind very limited requirements were provided upfront. The solution could be C function, a method or a category, and the signature for calling was undefined.
Read on to see four unique variations of how to convert an integer value into a binary NSString object.
With the release of iOS 7, Apple added support for encoding and decoding data using Base64. In this post we will walk through two examples using Base64 to encode and decode both NSData and NSString objects.
First, we will create an NSString object that is generated by Base64 encoding an NSData object. This will be followed by decoding the Base64 NSString back into an NSData object. We will display the NSString data, both encoded and decoded to make sure all is well.
The second example will encode and decode NSData to/from Base64. This example is relevant if you have an NSData object that needs to be Base64 encoded, or you need to decode a Base64 NSData object (for whatever reason).
Here’s a quick way to count the number of words in an NSString object. The trick is to use the character set whitespaceAndNewlineCharacterSet which will look for spaces, tabs and newline characters.
- (NSUInteger)wordCount:(NSString *)str
NSUInteger words = 0;
NSScanner *scanner = [NSScanner scannerWithString: str];
// Look for spaces, tabs and newlines
NSCharacterSet *whiteSpace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
while ([scanner scanUpToCharactersFromSet:whiteSpace intoString:nil])
If you have another way to reach the same result, please post a code sample.
When poking around NSString methods you’ll find many references to NSRange, which is nothing more than a C structure that is helpful for describing a series of items, including a starting location and a count. For example, a range is helpful to extract a substring from another string, where you specify the starting location and number of elements needed (examples to follow).
NSRange is a structure defined as follows:
typedef struct _NSRange