Post

Use NSUbiquitousKeyValueStore to Help Save Small Settings in iCloud

Use NSUbiquitousKeyValueStore to Help Save Small Settings in iCloud

Use NSUbiquitousKeyValueStore to Save Small App Settings in iCloud

Sometimes, a small flag in an app is important enough that it should not disappear after the user deletes and reinstalls the app.

In MeowCare, we use NSUbiquitousKeyValueStore to save lightweight flags in iCloud, so they can survive reinstall and continue following the user’s Apple ID.

Why Use It

Some values are small, but they help prevent real problems.

For example:

  • dataOwnershipRole
  • hasSeededCareEvents

These are not large data objects. They are just small settings or lightweight state flags, which makes NSUbiquitousKeyValueStore a good fit.

Use Case

In MeowCare, we moved two flags from UserDefaults to NSUbiquitousKeyValueStore:

FlagPurposeWhy UserDefaults Is Not Enough
dataOwnershipRoleRecords whether the user is an owner or a participantAfter reinstall, the role is lost, and a participant may accidentally see or use the import feature
hasSeededCareEventsRecords whether sample data has already been importedAfter reinstall, the flag disappears, the seed process runs again, and data in iCloud may be duplicated

What NSUbiquitousKeyValueStore Is Good For

NSUbiquitousKeyValueStore is Apple’s iCloud Key-Value Storage API.

It is suitable for saving small values such as:

  • flags
  • simple settings
  • short strings
  • lightweight app state

It is useful when the value should:

  • survive app reinstall
  • follow the user’s Apple ID
  • sync across the user’s devices

Important Setup

If you use NSUbiquitousKeyValueStore, you must enable the iCloud Key-value storage capability in Xcode.

Otherwise, you may see this error at launch:

1
2
3
Unable to find entitlement for KVS store
BUG IN CLIENT OF KVS: Trying to initialize NSUbiquitousKeyValueStore without a store identifier.
Please specify your store identifier in the 'com.apple.developer.ubiquity-kvstore-identifier' entitlement.

In Xcode:

Target → Signing & Capabilities → + Capability → iCloud → check Key-value storage

After enabling it, Xcode will add this entitlement automatically:

1
2
<key>com.apple.developer.ubiquity-kvstore-identifier</key>
<string>$(TeamIdentifierPrefix)$(CFBundleIdentifier)</string>

Summary

If you only need to preserve small settings or lightweight flags in iCloud, NSUbiquitousKeyValueStore is a simple and suitable choice.

In our case, it helps keep important flags such as role information and seed-completion state from being lost after reinstall.

This post is licensed under CC BY 4.0 by the author.