2012年1月25日水曜日

Auto incrementing build number in Xcode

In one of my apps I have data as csv files in the bundle and at when the app is run for the first time I parse these files and create a database using Core Data. During development I often added more data to the csv files, adjusted the Core Data classes and so on, so I needed a smooth way of telling whether the app was run for the first time or not since the last build so I can reconstruct the database.

I first tried another solution that didn't require the target name "MYTARGET" in the script which means you don't have to customize the script for every project but I couldn't get that to work in Xcode 4.2 but here is a script that works great for me. I will link to the source if I remember it later.

In the project navigator, select your project and then your target to the right.
In the "Info"-tab, create a new "Custom iOS Target Property" called "BuildNumber" and let it be a string.
Select the tab "Build Phases" and "Add Build Phase" down to the right.
Select "Add Run Script" and set the shell to "/bin/bash"
Paste in this script: (replace MYTARGET with the name of your target (usually same as name of project)

#!/bin/bash
buildNumber=$(/usr/libexec/PlistBuddy -c "Print BuildNumber" MYTARGET/MYTARGET-Info.plist)
buildNumber=$(($buildNumber + 1))
/usr/libexec/PlistBuddy -c "Set :BuildNumber $buildNumber" MYTARGET/MYTARGET-Info.plist

bundleShortVersion=$(/usr/libexec/PlistBuddy -c "Print CFBundleShortVersionString" MYTARGET/MYTARGET-Info.plist)
bundleVersion=$bundleShortVersion"."$buildNumber
/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $bundleVersion" MYTARGET/MYTARGET-Info.plist

Now, each time you build your app the variable "BuildNumber" will be increased by 1 and your bundle version will be set to Version.BuildNumber. That is, if your app version is 1.0 and your on build number 8, the bundle version will be 1.0.8.

If you, in your app delegate or elsewhere, want to check if the "BuildNumber" has changed since the last run by comparing it with the last value, stored in NSUserDefaults, do something like:

int thisVersion = [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"BuildNumber"] intValue];
int lastVersion = [[NSUserDefaults standardUserDefaults] integerForKey:@"lastVersion"];
[[NSUserDefaults standardUserDefaults] setInteger:thisVersion forKey:@"lastVersion"];
BOOL appIsNewVersion = lastVersion != thisVersion;

And there, you have a smooth, automated way of telling if you're on a new build and do the proper initializing, etc.

記載されている会社名、および商品名等は、各社の商標または登録商標です。

0 コメント:

コメントを投稿

Related Posts Plugin for WordPress, Blogger...