Yearly Archives: 2018

Building a Day Counter on iOS

In this video series I’ll show you how to create a simple Day Counter on iOS, using Objective-C and Xcode 9. The idea is to set a date in a settings screen, and then see how many days have elapsed on the main screen right after launching the app.

This is a 3-Part Mini-Series: Continue reading





How to pick a random character from a string in Objective-C

Imagine we had an NSString consisting of a pool of characters from which we’d like to pick one at random. Say our pool is ABCDEFGHIJKLMNOP, and we want a single character.

Here’s how we can do that:

// pool of characters
NSString *characters = @"ABCDEFGHIJKLMNOP";

// create a random number 
// between 1 and however many characters we have in the pool
uint32_t length = (uint32_t)characters.length;
NSUInteger random = arc4random_uniform(length);

// make a range
NSRange range = NSMakeRange(random, 1);

// pick a random character from the pool
NSString *letter = [characters substringWithRange:range];

The comments speak for themselves. One thing of note is the typecast of characters.length, which is needed to suppress the Xcode warning “implicit conversion loses integer precision”.

Most of the magic is provided by the NSString method substringWithRange.