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.

Every iOS and Mac Developer Needs a Watchdog

Today, Cerebral Gardens introduces Watchdog for Xcode. Watchdog is a helpful utility for iOS and Mac OS X developers that monitors Xcode cache files (DerivedData) and cleans out stale files before they interfere with your builds.

If you’ve been building apps in Xcode for a while, you will see the value in Watchdog instantly as you are familiar with the weird errors that can happen with Xcode. If you’re new to using Xcode, you may not have run into these issues yet, but eventually you will and that’s when Watchdog will save immense time and frustration.

A Watchdog user will no longer see these weird issues:

  • Old images that you've replaced, still showing up in your app.
  • The DerivedData folder growing continuously over time, often taking up 10+ gigabytes of space.
  • Constants/Defines not updating in the app after you've changed them in the code.
  • Localization file changes not being seen.
  • Phantom breakpoints and/or breakpoints stopping on the wrong line.
  • Xcode refusing to run a build on your device, only reporting something obscure like: "Error launching remote program: No such file or directory"

Sometimes the cause is related to your version control system updating files without Xcode noticing. Sometimes it’s random. Regardless, the result is the same: a bad build, time wasted, a frustrated developer, or even worse, an annoyed customer.

These errors can be mind numbing. Let Watchdog be your guard against these errors so you never again have your time wasted.

Watchdog gives you truly clean builds, saves time, and your sanity. It guards, protects and, most importantly, prevents.

Download Watchdog for Xcode

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.

TestFlight Your Apps

You've been working on your new app for ages and it's finally ready for beta testing. Prior to iOS 4.0, it was a considerable pain in the neck to get a build on to your testers devices. You needed to package up your apps and ad hoc profile, send them to each tester, and then they needed to use iTunes to install the profile and app on their device. It seemed like an art more than a science getting an app installed, never mind an updated build later. It was a very clunky system, and it didn't always go smoothly.

With iOS 4.0, Apple made it much easier to install test apps on a device. It's now possible to install profiles and apps without going through iTunes. Using XCode's Build and Archive option, you can create an .ipa file that embeds the ad hoc profile. Just put the .ipa file on a web server, (or your public Dropbox folder), and send the link to your testers. They can install the build by clicking the link in mobile Safari.

You're still required to collect your users UDID's, add their devices to your developer account and create an ad hoc profile that includes their devices.

Last week, TestFlight, a new service for distributing your test builds to your beta testers, went live. TestFlight promises to revolutionize the way developers beta test their apps, and after testing it out for a bit, I'm pretty sure they're going to do just that.

The free service, found at testflightapp.com, allows a developer to invite people to become a beta tester. The tester creates an account through the web site in Mobile Safari on their device, and then they register their device with the system. This process involves installing a configuration profile (different from an ad hoc profile, but listed in the same area on the device's settings). This gathers the device UDID and reports it back to the server. A tester can register more than one device. The tester, and her device(s) then show up in the developer's account. As a developer, you can export the UDID's of all your testers and import them into Apple's iOS Provisioning Portal. One issue I found here though, is that if you attempt to import a file of UDID's that contain a record that you've already added to the Portal, it will reject the entire file, instead of just ignoring that record.

Once you've imported all the new UDID's into the iOS Provisioning Portal, you can update your ad hoc profile to include all of your testers. Then, use it to create a test build of your app. You still need to use XCode's Build and Archive Option, and then use it's sharing wizard to create the .ipa file (all in all, a simple process, more details here: http://iphonedevelopment.blogspot.com/2010/05/xcode-32-build-and-archive.html).

Next, you upload your .ipa file to the TestFlight web site, and select the testers you'd like to notify of the new build. TestFlight emails each of them a link to a page that lets them install the build easily.

TestFlight lets you see how many times the .ipa file was downloaded (though, not by whom for some reason). I had one person delete it from their phone and redownload it, and it counted as another download. So a list of 5 people, with 5 downloads, doesn't really mean they all downloaded it. But it will likely be close.

I tested this entire process with some extremely non-technical people, not one had an issue. They were all able to create their accounts, register their devices, and install my test app with ease.

If you need more beta testers, TestFlight offers a recruitment tool. You can start recruiting random people through Twitter, your web site, or wherever. It's just a link you post. When people sign up to be a beta tester for you, you can accept or reject them based on whatever criteria you like.

Overall, I'm very impressed with the initial service offering TestFlight has. And, remember, it's entirely free (for now) for developers. They are charging for enterprise accounts.

I do have to point out one concern I have with TestFlight however. During my limited testing of the service over the last couple of days, I uploaded a few builds, sent them out to some testers, including myself, and then deleted the builds. When I went back to one of my test devices, I still had the link open in Safari to do the install, for a build that I had deleted in the TestFlight dashboard. So, I tested, and tried to install the build, that should have been deleted. It installed perfectly. This is my concern, because I had deleted the build! Which means, that TestFlight, is not actually deleting the bits of the builds you tell it to delete, it's just removing them from your dashboard. Whether or not you consider this acceptable is up to you (and your personal level of paranoia) . But remember, that when you upload your .ipa to TestFlight, you're letting unknown people view and test your ideas (yes, the TestFlight people can view and run your .ipa files, if they so choose).

If you are concerned, you can use Hockey to manage your beta installs. It's not as easy to manage as TestFlight, but you con trol everything on your servers so it's arguably more secure.

You can even mix and match some of the TestFlight features (UDID collection, recruitment etc), and then deliver the actual builds via Hockey.

Paranoia aside, TestFlight is excellent so far, and will change the way you deliver your test builds to your testers. Down the road, they plan to support additional features, such as adding analytics so you can view what your testers tested and for how long.

Dev Tips & Tricks

Today I'm going to cover some useful tips and tricks. These are presented in no particular order, and are pretty much unrelated to each other. Hopefully you'll find some, or all of them useful.

1. Regarding the upcoming iPad 2

Reports are starting to surface that the next version of the iPad will support a retina type display. Apple will no doubt repeat what they did with the iPhone 4 and double the resolution (4 times the number of pixels). This makes it easy to support old apps on the new device by employing pixel doubling.

But, you can start preparing for this now! For every iPad image you use, include a higher resolution (double sized) image with the @2x suffix. And for icons, include a 144x144 (double 72x72) icon. I've included a 144x144 icon in all my iPad apps since the iPhone 4 was announced, betting on Apple doubling the iPad resolution. It's cheap to do, and if the predictions are wrong, there's no harm in having an unused icon.

As a sub tip, you should include the following sizes for your icons: 144x144, 114x114, 72x72, 58x58, 57x57, 50x50, 29x29

2. self.var vs var

In your classes, when use the following syntax:

DWClass.h

@interface DWClass : NSObject {
    NSObject *myObject;
}

@property (nonatomic, retain) NSObject *myObject;

DWClass.m

@synthesize myObject;

You're telling the compiler that your new class DWClass will have a property called myObject, and that it should create setMyObject (setter) and myObject (getter) methods to access that property. And that those methods should handle your retain/release cycles for you. Any other objects that need to interact with your myObject property, will do so by like this:

dwClass.myObject // (assuming dwClass is an instance of DWClass)

And this will actually call the appropriate setter/getter for the myObject property, which in turn interacts with the myObject instance variable of the dwClass.

Inside the DWClass however, you can access the property like this:

self.myObject

And the same setter/getter methods are used.

Inside the DWClass, you can also access the myObject instance variable directly just by referencing it. DO NOT do this. If you do that, you're not using the setter/getter methods, which means you're not automatically handling the retain/release calls. This is a surefire way to create hard to find bugs in your code. Plus, there are other problems with doing this. If down the road, you need to do something special whenever that property is accessed or updated, so you ditch the @synthesize and create your own setter/getter methods, you're now going to miss even more than the retain/release calls, you're going to miss whatever else you've added.

This entire tip also applies to non-object properties. Even if you're using a standard int as a property, always use the self.variable syntax to access it. It's just good practice and will save you headaches down the road.

3. Keeping your secrets, secret

Often when you're accessing other services, Twitter, Dropbox, your own servers etc, you may need to store passwords, API keys, etc in your code. It's dead easy to just have a constant like this: @"MySuperSecretKey" and be done with it. If you do that though, you may as well post the secret on your web site for all to see. Since, it's trivial for a bad guy to extract your secret from the compiled code they download from the App Store after your release. This is a bad thing. In the case of Twitter for example, some spammer could put your secret key into a rogue app that spam blasts users. Every one of those tweets will say it was sent by your app, and your legit app will be blocked pretty quickly. Your users will be locked out until you submit a fix and have it approved by Apple, say goodbye to two weeks of sales, not to mention, all the bad reviews you'll receive for selling a non-functioning app.

So, keep your secrets secret, use some encryption inside of your app to encrypt your keys etc. It doesn't have to be complex as the bad guy usually just looks for low hanging fruit (unless they are specifically targeting you). You can use one of the many encryption libraries available, or even roll your own if you're so inclined.

4. Ensure the App Store knows you support multiple languages when you do so

This tip comes from a mistake I made in version 1.0 of the Cruze app. The app supported English and French from the get go, but it was done by detecting the language of the user via code and loading the correct set of files for the primary language. This worked great and was way less work than using Apple's recommended method of localization for every nib etc.

One problem though, once the app was released to the store, the only supported language listed in iTunes was English. Because I used my own language detection iTunes Connect didn't detect French. I fixed this in 1.5 by using Apple's localization on a small dummy text file. One that I don't actually use for anything in the app, but that is enough to trigger the language detection tools Apple uses.

Update: see Ovogame's comment below for an even better way to fix this issue.

5. AppName_Prefix.pch

There's a file in your XCode project named AppName_Prefix.pch (where AppName, is your app's name). This file is included at the top of every source file in your project. It's a great place for you to store any constants you need across your app.

6. A Better NSLog()

A common method of debugging is to add NSLog() calls throughout your code. The messages are echoed to the screen as the code runs and you can see what's happening, giving you hints as to what's causing bugs. When you're finished however, and you want to do your final build, all of those NSLog() calls remain in your final build and all of those strings are available for anyone looking through your binaries to see. Who knows what secrets you might disclose.

Instead of using NSLog(), I use DebugLog(). This is a tweak of a function I’ve seen others use, based on the answer here: http://stackoverflow.com/questions/300673/is-it-true-that-one-should-not-use-nslog-on-production-code.

Add this to your AppName_Prefix.pch file:

#ifndef DebugLog
#ifdef DEBUG
#define DebugLog( s, ... ) NSLog( @"<%p %@:(%d)> %@", self, \
	[[NSString stringWithUTF8String:__FUNCTION__] lastPathComponent], __LINE__, \
	[NSString stringWithFormat:(s), ##__VA_ARGS__] )
#else
#define DebugLog( s, ... )
#endif // DEBUG
#endif // DebugLog

Now, replace all of your NSLog() debugging statements with DebugLog(), and define DEBUG in your debug configuration (sub tip 2: go to your Project Info, Debug configuration, search for Preprocessor Macros, add DEBUG).

After this, use DebugLog() all you like, and the strings are skipped over in your Release and Distribution builds. You also have the added bonus of having the function name and line number included with all debug statements now, making it clear what's generating the messages.

7. *.dSYM files

Whenever you build your app, XCode will output the *.app files, as well as a *.dSYM file. For Debug and Release builds, you can just toss/ignore the *.dSYM file. But for your distribution build, that you're going to submit to the App Store, make sure you keep the .dSYM file. You'll need this later, to analyze crash reports. I'll go into more detail on this in a later post, just know you need to keep the files. For the impatient, you can read more on this here: http://www.anoshkin.net/blog/2008/09/09/iphone-crash-logs/

8. Push Notification Certificates

If you have an app that uses push notifications, you need to generate a certificate with Apple, one of the first steps, is to create a Certificate Request file (CertificateSigningRequest.certSigningRequest), that you send to Apple. Keep this file. When your certificate expires, you'll need to request a new one. You can reuse the same Certificate Request file and skip the first few steps.

9. [object release]; object = nil;

With NSObjects, when you're done with them, you call release to reduce the retain count and let the system know you no longer need it. When that retain count hits 0, the system free's the object and releases the memory allocated back for use later.

It is common practice, to set the object to nil after you call release. This prevents a possible crash later, if you attempt to call a method on an object that has been freed. That's because if you try to call a method on a nil object, the system just ignores it, no error, all is good (or is it). If you don't set the object to nil, then it will still point to the memory address that was allocated for that object. There's a chance that object is still there (if something else was using it and increased the retain count for example). In that case, calling a method on that released object, will still work. But if that memory had actually been released calling the method would cause a crash.

This is why developers often set the object to nil, to prevent that crash in the case of a bug. But, this doesn't fix the bug, it just hides it from you. So, I subscribe to the second school of thought you shouldn't set the object to nil. If you have a bug, let the app crash while you're developing and you'll be able to find and fix that bug. When you no longer have any crashes, you'll know you're (closer to being) bug free, and that you haven't just masked your bugs.

Three’s Company: Multiple XCode Versions Living Together Peacefully

Apple is making fantastic progress with iOS. They continue to release firmware updates and betas at a frequent pace, and with each new release, developers must download and install a new version of XCode compatible with the new firmware. Managing the various versions and their associated firmwares can be a challenge. In this article I'm going to give you a couple of tips that will hopefully help.

It's not uncommon for developers to have multiple versions of XCode installed on the same system in order to support development/testing across a wide range of devices and firmware versions. XCode by default installs in /Developer, and it is common practice to install the latest beta version in /DeveloperBeta. Those testing XCode4 know its default install folder is /XCode4. Personally I found this to be messy and inadequate.

My preferred setup now is to create a directory /XCode and install each version of XCode underneath using the version info as it's base folder name. Currently this looks like this:

/XCode/3.2.3_4.0.2
/XCode/3.2.4_4.1b3
/XCode/xcode4_dp2

When installing XCode in this fashion, you’ll find that in some cases, you won’t be able to install/debug a build on one of your devices because of a mismatch in firmware versions. For example, the XCode 4 Developer Preview 2 was released before firmwares 4.0.2 for iPhone and 3.2.2 for iPad. So if you’ve updated your devices to those firmwares, you’re now unable to use XCode 4 to directly install or debug.

There is a simple fix however. You just need to create symlinks from one version of XCode to another. Assuming you’re using a layout similar to what I’ve detailed above. If you look under /XCode/xcode4_dp2/Platforms/iPhoneOS.platform/DeviceSupport you’ll see folders for each version of iOS that you can install/debug on. 3.2.2 and 4.0.2 are obviously missing. If you’ve installed the latest version of XCode 3 with support for those versions, you can make XCode 4 work with them.

In terminal, issue the following commands to create the required symlinks:

ln -s /XCode/3.2.3_4.0.2/Platforms/iPhoneOS.platform/DeviceSupport/4.0.2 \
	/XCode/xcode4_dp2/Platforms/iPhoneOS.platform/DeviceSupport
ln -s /XCode/3.2.3_4.0.2/Platforms/iPhoneOS.platform/DeviceSupport/3.2.2 \
	/XCode/xcode4_dp2/Platforms/iPhoneOS.platform/DeviceSupport

Similarly, If you’re using the 4.1 beta 3 firmware on your iPhone, you’ll need XCode 3.2.4_4.1b3 installed, and can then enable support for that firmware version in XCode4 also:

ln -s /XCode/3.2.4_4.1b3/Platforms/iPhoneOS.platform/DeviceSupport/4.1\ \(8B5097d\) \
	/XCode/xcode4_dp2/Platforms/iPhoneOS.platform/DeviceSupport

If you have your XCode versions installed under a different directory structure (/Develper, /DeveloperBeta, and /XCode4 etc), you’ll just need to tweak the above lines to point to the correct folders.

A similar trick can be used to allow you to use a base SDK of 3.1.3 or earlier, which is no longer included in the latest versions of XCode. Just create links under the /XCode/Platforms/iPhoneOS.platform/Developer/SDKs to an older XCode that does include support for the SDK you need.

If you have any tips to improve upon this, see an error in what I’ve described, or otherwise have anything else to contribute, please let me know.