Our BlogTips, Tricks, and Thoughts from Cerebral Gardens

Mix and Match Swift 3 & Swift 4 Libraries with CocoaPods

With Xcode 9, it’s possible to mix and match Swift 3 and 4 libraries together. In the build settings for the project you set the version of Swift to use by configuring the SWIFT_VERSION setting. You’re able to override the project setting at the target level, thereby building some targets with Swift 3, and others with Swift 4.

If you’re using CocoaPods as your dependancy manager, there’s an issue when mixing and matching.

As you know, when using CocoaPods, you end up with an Xcode workspace that contains your main project, and a Pods project. Whenever you run pod install or pod update, CocoaPods will set the SWIFT_VERSION for all targets to be whatever your main project is set to, or it will fallback to Swift 3 if the main project doesn’t have the SWIFT_VERSION specified.

This means Xcode will try and compile all targets with the same version of Swift, regardless of what version of Swift is actually needed. There’s no built-in way for you to specify the version of Swift to use for each pod you’re including. There is a way for the pod maintainer to specify the version needed in the podspec (they need to set pod_target_xcconfig = { 'SWIFT_VERSION' => '4.0' } see XCGLogger.podspec for an example), but I’ve found it’s rare at this time for it to be set (hopefully this post will help change that).

Even if the pod sets the version of Swift to use, we run into a problem when Xcode resolves the setting. Xcode will prefer the target’s direct setting over the podspec’s suggestion, and since pod update always sets a direct setting on the target, the pod spec’s suggestion is never used (not surprising it’s rarely set).

The solution is to add a post_install script to the end of your podfile:

Let's examine this script.

It’s a post_install script so CocoaPods will execute the script after is has updated all of the included pods and updated the project file.

The script starts by looping through the build configurations of the Pod project and sets the default Swift version to 4.0 (lines 2-5).

Then it loops through all of the project’s targets (lines 7-19). It checks the target name against a known list of targets (line 8) and sets each of the configurations for matching targets to Swift 3 (lines 10-12). If the target isn’t in the known list, the script unsets the Swift version (lines 15-17), which will allow the pod to set the version itself using the pod_target_xcconfig setting we noted above. If the pod doesn’t set the version, Xcode will use the default Swift version we set at the start.

You will need to tweak the script for your project, specifically to set your default Swift version, and then to add the targets that require a different version on line 8.


If you’ve found this article helpful, please subscribe to the RSS feed and follow me on Twitter

It would be awesome if you’d download our new app All the Rings. It’s free and we really think you’ll like it!

If you see any errors, want to suggest an improvement, or have any other comments, please let me know.

Introducing Party Doodles, and the Lessons It Has to Share

Last Wednesday we released our newest game, Party Doodles. A unique picture guessing game that uses AirPlay mirroring to create a party game experience unseen before now on the App Store. It has been in the works since AirPlay mirroring was announced (yes, almost a year from concept to release).

I believe, and app reviewers (here, here, and here) seem to agree, that Party Doodles is the first of it's kind on the App Store. The tag line for the game is 'Made for iPad, designed for Apple TV' because while you can play without Apple TV, the game is really meant to be played on the Apple TV.

The easiest way to describe the game, is to compare it to Pictionary. A group of friends break into two teams, each person takes a turn drawing clues (on the iPad) while their teammates try and guess what it is (watching on the big screen TV) before time is up. If time runs out, the other team can steal the points. I added some strategy to the game by having 3 difficulty levels baked into each turn, the person doodling can pick an easy topic to win 1 point, a medium topic for 2 points, or a hard topic for 3 points. If you're behind the other team it gives you a chance to catch up, or if you're winning, a chance to get even further ahead!

The game really is a lot of fun, and I'm not just saying that cause I made it. I had people actually come over to my house and ask to play it. And it's not uncommon for players to break out into uncontrollable laughter.

Anyway, enough plugging the game, please download it and give it a try. Did I mention it's free?

On to what lessons the game has for us, as developers....

First, it's important to know that progress on the game was sometimes slow as I was working full time at a normal job when I first started working on the game. Even when I went full time indie, client projects usually take precedence and consume the majority of my time. I recently looked back at my source commits and noticed several months where I hadn't committed a single line.

A lot of things happened over the course of the development of the game. One of which was that Draw Something came out and became a massive hit. There was a definite 'Oh shit' moment at that point. But it didn't take long to come to terms with the fact that the games are significantly different. I never intended Party Doodles to have mass market appeal anyway. It's definitely for a niche market since the requirements to play properly are high; you need:

  1. an iPad
  2. an Apple TV
  3. actual friends in the same room1

The goals for Party Doodles were to create a unique experience doing something that no other app on the store was doing yet (I expect more will come along shortly), to try the freemium model out, to create a fun game that people can really enjoy playing together, and to get a little attention for the game itself since it is the first of it's kind on the App Store, not an easy feat nowadays.

I've definitely learned a lot while developing this game and plan to share a bunch of tips/tools and code over the next few blog posts. Today's tip is a short one though (since I used up so much space detailing the game in the first place).

When releasing an app with In-App purchases, make sure you test the purchase functionality with the live app from the App Store as soon as it's available. (Use a promo code to download the app after it's approved and before it's released if need be). There are some slight differences between the Production IAP system and the sandbox we can get to test with before submission. In my case, I added receipt verification as suggested by Apple (using PHP on the server, with code I'll likely share in a later post) and the verification process would fail on production requests only due to a minor difference in data sent back from Apple. That caused the first few purchases to be rejected. Not a good user experience at all! Even Apple's reviewers test the app in the sandbox and thus missed my production only bug.

Fortunately I was able to fix it fast since it was just server side code and not in-app code that needed to be changed.

Ok, lots more to come in future articles so stay tuned. In the meantime, please download the game, and like us on Facebook.

1As a french review (Google Translation) of the game pointed out, you also need a TV which they said makes my free game very expensive. I hadn't considered that someone would add the TV to the cost of my game.

Enumeration of NSMutableArray's Follow Up

Today I'm going to follow up on some interesting comments to my previous tip regarding enumerating NSMutableArray's.

I had suggested to make a copy of the mutable array before enumerating, in order to prevent another thread from modifying the array you're working on and causing a crash.

It was mentioned that making that copy is itself an enumeration and so we were just moving the crash point. So, I did some digging.

// array is an NSMutableArray
- (IBAction)button1TouchUp:(id)sender
{
    DebugLog(@"Populating Array");
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
    ^{
        for (int i = 0; i < 10000000; ++i)
        {
            [array addObject:[NSNumber numberWithInt:i]];
        }
        DebugLog(@"Done Populating Array: %d", [array count]);
    });
}

- (IBAction)button2TouchUp:(id)sender
{
    DebugLog(@"Enumerating Array");
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
    ^{
        DebugLog(@"Copying Array");
        NSArray *copyOfArray = [array copy];
        DebugLog(@"Done Copying Array");

        long long x = 0;
        for (NSNumber *number in copyOfArray)
        {
            x += [number intValue];
        }
        DebugLog(@"Done Enumerating Array: %d", [copyOfArray count]);
    });
}

Note: if you test this, do so in the simulator, a device will generate a memory warning and shutdown the test app.

The idea here is that by touching button1, we create a large array in a thread, and touching button 2, we enumerate that array. The array is large enough that it gives you time to ensure you touch button 2 while button 1's thread is still populating the array. If you didn't create the copy of the array before enumerating it button 2, the app will crash. Using the copy of pattern I mentioned in the last post, prevents that crash as expected.

Taking this a little further, the test code shows that when you take a copy of the mutable array, you get a copy of it at in its current state. If something is altering the array when you make the copy, you could get a copy of the array in an unusable or unexpected state. If you were adding or removing elements for example, you might have half of the elements in your copy while expecting all of them, or none of them.

If you need to ensure changes to an array are completed in full before another thread accesses it, you can use the @synchronized directive. The modified code looks like:

- (IBAction)button1TouchUp:(id)sender
{
    DebugLog(@"Populating Array");
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
    ^{
        @synchronized(array)
        {
            for (int i = 0; i < 10000000; ++i)
            {
                [array addObject:[NSNumber numberWithInt:i]];
            }
            DebugLog(@"Done Populating Array: %d", [array count]);
        }
    });
}

- (IBAction)button2TouchUp:(id)sender
{
    DebugLog(@"Enumerating Array");
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
    ^{
        @synchronized(array)
        {
            DebugLog(@"Copying Array");
            NSArray *copyOfArray = [array copy];
            DebugLog(@"Done Copying Array");

            long long x = 0;
            for (NSNumber *number in copyOfArray)
            {
                x += [number intValue];
            }
            DebugLog(@"Done Enumerating Array: %d", [copyOfArray count]);
        }
    });
}

The @synchronized directive creates a lock on the object for you.

A few points to be aware of:

  1. you need to use @synchronized around all places where you need to lock the object.
  2. the code will block until the object can be accessed, so if thread A is using the object thread B will pause until thread A is done with it, so be sure not to create a block on the main thread.
  3. if you define a property on a class as atomic, by omitting the non-atomic keyword, the synthesized accessors will include synchronization code and simply the code for you, but you still need to be aware of the blocking issues.

As always, I love reader feedback. Especially when you point out my mistakes, since that's the fastest way to learn more.

A Simple Tip to Avoid Crashes

As you may be aware, I went full time indie a couple of months ago. I've been working almost as many hours as I can stay awake for clients, and spending whatever extra time I can find on a new game that I hope will be finished and submitted to the App Store before my next blog! I can't wait to tell you guys all about it.

With all this work though, I've been slacking in the blog department. Today I start to correct that. Here's a quick tip for today that may save you from a few crashes tomorrow.

It's a common sight to see something like this in Objective-C, where you're enumerating through an array (that's mutable), and doing something to each of the objects:

// self.objects is an NSMutableArray
for (NSObject *object in self.objects)
{
    [object doSomething];
}

If your app is multithreaded, you'll get a crash if another thread adds to or removes from the array at the same time this loop is being processed. Depending on timing, you might not see this bug hit until the app is being used by users.

Instead, anytime you're going to run through an array like this, make a copy first and enumerate the copy. Now you're multithreaded safe.

NSMutableArray *copyOfObjects = [self.objects copy];
for (NSObject *object in copyOfObjects)
{
    [object doSomething];
}
[copyOfObjects release]; copyOfObjects = nil;

Here's another common pattern you'll see, when you're enumerating the array in order to remove certain elements from it. Because you know you can't remove objects from the array as you're running through it, you create another array to store the the objects you want to remove and then remove them in a second step:

NSMutableArray *objectsToRemove = [[NSMutableArray alloc] init];

// self.objects is an NSMutableArray
for (NSObject *object in self.objects)
{
    if ([object shouldBeRemoved])
    {
        [objectsToRemove addObject:object];
    }
}
[self.objects removeObjectsInArray:objectsToRemove];
[objectsToRemove release]; objectsToRemove = nil;

Using the copyOf pattern above, you can remove the objects in a single step, since you're not actually enumerating the same array anymore:

NSMutableArray *copyOfObjects = [self.objects copy];
for (NSObject *object in copyOfObjects)
{
    if ([object shouldBeRemoved])
    {
        [self.objects removeObject:object];
    }
}
[copyOfObjects release]; copyOfObjects = nil;

Now you have nice, clean, efficient, crash free code.