Skip to content

Instantly share code, notes, and snippets.

@0x48piraj
Created May 4, 2025 03:37
Show Gist options
  • Select an option

  • Save 0x48piraj/db10517872ed989d438c47a6f197e0e1 to your computer and use it in GitHub Desktop.

Select an option

Save 0x48piraj/db10517872ed989d438c47a6f197e0e1 to your computer and use it in GitHub Desktop.
Clearing UserDefaults during debug builds from Xcode

Use a UUID marker on each build (works even if build number doesn't change)

If you want UserDefaults to clear every time you install a new Debug build via Xcode, regardless of version or build number, you can inject a unique marker that changes on every build.

πŸ”§ 1. In your Build Settings (not Info.plist), add a custom build variable:

Go to:

Build Settings β†’ User-Defined β†’ click +

Add:

Key: BUILD_ID
Value: ${CURRENT_PROJECT_VERSION}-${CURRENT_TIME}

Or just:

BUILD_ID = $(CURRENT_PROJECT_VERSION)-$(SOURCE_ROOT)

Then expose it to your code via Build Settings β†’ Swift Compiler β†’ Custom Flags:

Other Swift Flags: -D BUILD_ID="your-build-id-here"

But this is clunky.

Generate a random UUID at build time and bake it into the app (simpler)

Use a script to write a random UUID into Info.plist every time you build:

Add a Run Script Phase in Xcode

In your project:

Target β†’ Build Phases β†’ "+" β†’ "New Run Script Phase"

Paste:

uuid=$(uuidgen)
defaults write "${SRCROOT}/Info" BuildUUID "$uuid"

Or if you're managing Info.plist in Xcode directly:

/usr/libexec/PlistBuddy -c "Set :BuildUUID $(uuidgen)" "${TARGET_BUILD_DIR}/${INFOPLIST_PATH}"
import UIKit
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
#if DEBUG
let buildUUIDKey = "BuildUUID"
let defaults = UserDefaults.standard
let currentUUID = Bundle.main.infoDictionary?[buildUUIDKey] as? String
let lastClearedUUID = defaults.string(forKey: "lastClearedUUID")
if currentUUID != lastClearedUUID {
print("🧹 New Debug Build Detected – Clearing UserDefaults")
if let bundleID = Bundle.main.bundleIdentifier {
defaults.removePersistentDomain(forName: bundleID)
}
defaults.set(currentUUID, forKey: "lastClearedUUID")
}
#endif
return true
}
}
import UIKit
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
// force-clear on every debug launch (this wipes every launch, not just on install/update)
#if DEBUG
UserDefaults.standard.removePersistentDomain(forName: Bundle.main.bundleIdentifier!)
#endif
return true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment