NSUserDefaults
custom objects
iOS development
Swift programming
data persistence

How to store custom objects in NSUserDefaults

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

NSUserDefaults is a powerful feature in iOS development that allows you to save simple data persistently across app launches. While it's straightforward for storing standard data types like strings, numbers, or booleans, storing custom objects requires additional handling. This article will guide you through the necessary steps to store instances of custom classes in NSUserDefaults .

Understanding NSUserDefaults

NSUserDefaults provides a simple interface to interact with the user's defaults database. The data is saved persistently, which means it will remain intact even after the app is closed. This database is primarily used for storing user preferences, application settings, and other lightweight data.

Why Custom Objects In NSUserDefaults

?

There are scenarios where your app may require the persistent storage of more complex data types than what's natively supported by NSUserDefaults . You might want to save an entire object that has multiple properties representing specific application states or settings.

Basic Limitations

NSUserDefaults directly supports the following data types: NSString , NSNumber , NSDate , NSArray , NSDictionary , NSData , and NSURL . However, it does not natively support custom objects.

Storing Custom Objects

To store custom objects, you need to serialize your objects into a supported format. This is usually done by encoding your custom object into NSData using NSKeyedArchiver , which can then be stored in NSUserDefaults .

Step-by-Step Process

  1. Adopt the NSCoding Protocol:
    Your custom class must implement the NSCoding protocol to be archivable using NSKeyedArchiver . This involves two essential methods:
  • Secure Encoding: For sensitive data, always use secure coding with NSKeyedArchiver . Set requiringSecureCoding to true and ensure your custom objects adopt NSSecureCoding .
  • Error Handling: Properly handle errors in encoding and decoding operations to avoid app crashes.
  • Limitations: Be mindful of the amount of data you store, as NSUserDefaults is not intended for large datasets. For larger objects, consider using a database like Core Data.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.