Phase 3: Native Development

Key-value storage: UserDefaults, SharedPreferences & MMKV

Intermediate ~2 min read
Think of it this way A friendly analogy. Read this if the technical version feels dense. Show Hide

Have you ever used an app, maybe a game or a drawing program, and noticed that it remembers things about you? Like your high score, or your favorite color setting, or even which level you were on last time? It's like magic, but it's really clever programming! Imagine your school locker or your backpack. When you put your history textbook in your locker, you put it in a specific spot, right? You might even have a mental label for that spot, like "Textbooks shelf" or "Top bin." You know exactly where to put it so you can find it easily next time.

In programming, we have something very similar called "key-value storage." Think of the "key" as that specific label or designated spot in your locker or backpack – like "Lunchbox Pocket," "Science Folder," or "Favorite Pen Holder." The "value" is the actual item you put into that spot – your sandwich for lunch, your science homework, or your lucky pen. You give each important piece of information a unique "name tag" (that's the key) and then store the information itself (the value) under that tag.

So, when an app needs to remember something, it does the same thing. It takes a piece of information, like whether you prefer "Dark Mode" on your screen, and gives it a key, maybe "ScreenTheme." Then, it stores "Dark Mode" as the value for "ScreenTheme." Later, when the app opens again, it just asks for the "ScreenTheme" key, and boom! It gets "Dark Mode" back and knows exactly how you like your app to look. It’s perfect for little things like remembering if you’re logged in, or what volume you like your game sounds to be, but not for storing every single picture you’ve ever taken.

This means when you build your own apps, you'll be able to make them super smart. You can make your apps remember user choices, progress in a game, or personal settings, just like your locker remembers where you put your favorite comic book, so it’s always there waiting for you the next day. This makes apps feel more personal and helpful, because they remember what you like and need.

When developing mobile applications, you often need to store small bits of data persistently, like user preferences, application settings, or a user's logged-in status. This is where key-value storage comes in. It's the simplest form of local persistence, allowing you to store data as unique key-value pairs, much like a dictionary or hash map. You assign a unique string key to a piece of data (the value), and later retrieve that data using the same key. This approach is ideal for lightweight data that doesn't require complex querying or relationships, offering a quick and straightforward way to make data persist across app launches.

Both major mobile platforms provide their own robust, built-in key-value storage solutions. For iOS and macOS, you'll use UserDefaults. It's a convenient API primarily used for storing user defaults, configuration settings, and small cached data. On Android, the equivalent is SharedPreferences, serving the same purpose of managing user preferences and simple application state. Both UserDefaults and SharedPreferences are generally synchronous, meaning operations block the main thread, and are optimized for quick reads and writes of primitive types (strings, integers, booleans, floats) or small data structures (like arrays of strings). They are perfect for "fire-and-forget" data persistence.

While UserDefaults and SharedPreferences are excellent for many basic needs, some scenarios demand higher performance or cross-platform consistency. This is where solutions like MMKV come into play. Developed by Tencent, MMKV is an efficient, high-performance key-value storage framework that's significantly faster than native solutions, often achieving an order of magnitude improvement in performance. It's cross-platform (iOS, Android, macOS, Windows, Web, etc.) and uses memory-mapped files to provide extremely fast reads and writes. MMKV is a strong candidate when you need to store slightly larger key-value datasets, require faster operations, or want a unified key-value storage solution across your multi-platform codebase, going beyond simple user preferences.

Key Takeaways

  • Key-value storage is for simple, small data like settings, flags, and user preferences.
  • UserDefaults (iOS) and SharedPreferences (Android) are the platform-native, built-in solutions.
  • MMKV is a high-performance, cross-platform alternative for faster or slightly larger key-value storage needs.
  • These are not suitable for large, complex, or relational data; use full databases for those cases.

Code Example

swift
import Foundation

// Storing a value
UserDefaults.standard.set("Kunal Ganglani", forKey: "username")
UserDefaults.standard.set(true, forKey: "isLoggedIn")
UserDefaults.standard.set(42, forKey: "lastVisitedPage")

// Retrieving a value
let username = UserDefaults.standard.string(forKey: "username") // "Kunal Ganglani"
let isLoggedIn = UserDefaults.standard.bool(forKey: "isLoggedIn") // true
let lastVisitedPage = UserDefaults.standard.integer(forKey: "lastVisitedPage") // 42

// Removing a value
UserDefaults.standard.removeObject(forKey: "lastVisitedPage")

How this code works

This Swift code illustrates how to use UserDefaults to store small pieces of user-specific information that needs to persist even after an app is closed and reopened. This is crucial for things like remembering a user's login status, their preferred settings, or the last page they visited, providing a seamless experience.

The code first stores data using UserDefaults.standard.set(value, forKey: "key"), assigning distinct string keys like "username" or "isLoggedIn" to various data types such as strings, booleans, and integers. These values can then be read back using type-specific retrieval methods, such as UserDefaults.standard.string(forKey: "username") or UserDefaults.standard.integer(forKey: "lastVisitedPage"). A key subtlety for beginners is that if a retrieval method is called for a key that doesn't exist, it will return a default value: nil for strings, false for booleans, and 0 for integers. Finally, UserDefaults.standard.removeObject(forKey: "lastVisitedPage") demonstrates how to completely delete a stored value, making it unavailable for future retrieval.