Core-Data Interview Questions And Answers.

Ravindra Bhati
12 min readSep 4, 2019

--

In this article, I will try to add as many Core data related to Interview Q&A. I will keep on updating this article. Hope it helps you guys 🙂.

In the iOS Application for saving data we are using Core Data.
In the iOS Application for saving data, we are using Core Data.

Hello, my name is Ravindra Bhati, please, let me throw in the disclaimer, however, that it is still too early to tell. As you will see during this or future posts, English it’s not my first language, so please if you are sensitive to grammatical crimes this is the best time for you to response on that, I ‘ll Correct as Soon.

I am an IOS developer, a self-taught one, a lot of curiosity and passion for coding. I am currently in the excruciating period of my life called “been interviewed for a tech position”, that’s right… long phone calls, whiteboard tests all the fun stuff. One wrong answer during your first interviews can determine if you get the job, or just a “thank you for participate”.

  1. What is Core Data?

Core Data is one of the most popular frameworks provided by Apple for iOS and macOS apps. Core data is used to manage the model layer object in our application. You can treat Core Data as a framework to save, track, modify and filter the data within iOS apps, however, Core Data is not a Database.

2. What is an object graph in Core Data?

An object graph is nothing more than a collection of objects that are connected with one another. The Core Data framework excels at managing complex object graphs. The Core Data framework takes care of managing the life cycle of the objects in the object graph.

3. What is NSManagedObjectContext?

The NSManagedObjectContext object manages a collection of model objects, instances of the NSManagedObject class. It is possible for an application to have multiple managed object contexts. Each managed object context is backed by a persistent store coordinator.

4. What is the core data stack?

Core Data consist of following stack objects:

  1. A managed object model.
  2. A managed object context.
  3. A persistent store coordinator.
  4. A persistent store (storage).

5. Is Core Data == SQLite or some wrapper?

Core data API is provided by apple for persisting data in SQL, XML, file system. It is not same as SQLite which involves disk I/O (input/output) operations. Most of the time core data uses in-memory objects (managed object context).

6. What types of stores does core data support?

Binary, XML, and SQLite.

7. What is Entity Inheritance?

An entity is a class definition in Core Data. The classic example is an Employee or a Company. In a relational database, an entity corresponds to a table.

NOTE:- Be careful with entity inheritance when working with SQLite persistent stores. All entities that inherit from another entity exist within the same table in SQLite. This factor in the design of the SQLite persistent store can create a performance issue.

8. What is an abstract entity in core data?

An Entity can be abstract, in which case it is never directly attached to a managed object.

An abstract object (in programming) or entity (in Core Data) is an object or entity that is never instantiated.

An entity is abstract if you will not create any instances of that entity. You typically make an entity abstract if you have a number of entities that all represent specializations of (inherit from) a common entity that should not itself be instantiated.

For example:- in the Employee entity, you could define Person as an abstract entity and specify that only concrete sub-entities (Employee and Customer) can be instantiated. By marking an entity as abstract in the Entity pane of the Data Model inspector, you are informing Core Data that it will never be instantiated directly.

9. What is a fetchedResultcontroller?

A controller that you use to manage the results of a Core Data fetch request and display data to the user in UITableView.

10. What is an NSManagedObjectId?

A managed object ID uniquely identifies the same managed object both between managed object contexts in a single application, and in multiple applications (as in distributed systems). Identifiers contain the information needed to exactly describe an object in a persistent store (like the primary key in the database), although the detailed information is not exposed. The framework completely encapsulates the “external” information and presents a clean object oriented interface.

11. What is Persistent store?

A persistent store is a repository in which managed objects may be stored. You can think of a persistent store like a database data file where individual records each hold the last-saved values of a managed object. Core Data persistent store file are: binary, XML, and SQLite

12. What is NSPersistentStoreCoordinator?

An object persists data to disk and ensures the persistent store(s) and the data model are compatible. It mediates between the persistent store(s) and the managed object context(s) and also takes care of loading and caching data. That’s right. Core Data has caching built-in.

Persistent Store Coordinator is actually the instances of “NSPersistentStoreCoordinator” class.👈👈👈

13. Can we do Multithreading with core data?

We can do multithreading in core data with multiple contexts, example background context for long-running tasks (batch inserting/fetching/updating) and update UI on the main thread.

14. What is the minimum necessary classes and the relationship between them?

We need NSManagedObject, NSManagedObjectContext and a Persistence store container. These classes/objects are the main building blocks of the core data stack.

Data operations like insert, update and delete are performed in managed object context. Managed object context can contain one or more managed object model instances. Persistence store coordinator communicates between managed object context and store.

15 Will you ever pass a managed object from one context to another context?

Or🤝🤝🤝

16. How to transfer manage object from one thread to another thread?

No, NSManagedObject instances are not intended to be passed between queues. Doing so can result in corruption of the data and termination of the application. When it is necessary to hand off a managed object reference from one queue to another, it must be done through NSManagedObjectID instances.

According to the Core Data concurrency rule, each thread must have its own managed object context. This is because NSManagedObjectContext and NSManagedObject, the two most fundamental objects in Core Data, is not thread-safe. They shouldn’t be initialized in one thread and accessed from a different thread.

17. What is lazy initialization, how does this relate to core data, situations when this can be handy?

When working with core data it is recommended to use a lazy keyword for lazy initialization of persistent container.

Due to lazy keyword the object will be initialized only when accessed. It is memory efficient technique used with some of the classes like DateFormatter, Calendar also. It also suits a business requirement where you have a model with it’s attributes.

18. Can the NSPersistentStoreCoordinator have more persistent stores?

Yes, but can’t create relationships between objects in different stores.

19. How to read only a few attributes of an entity?

We can use the NSFetchRequest class’s property “setPropertiesToFetch”. We can pass an array of properties in string format in setPropertiesToFetch method.

20. What is NSAsynchronousFetchRequest?

An asynchronous fetch allows developers to execute a fetch request without blocking the Managed Object Context for the duration of the fetch. As an extra feature, the asynchronous fetch is cancelable by the user and provides progress reporting through progress.

To fetch the data asynchronously in a background queue, Core Data provides the object NSAsynchronousFetchRequest.

21. What is Faulting mechanism in Core Data?

“When you retrieve an object from an NSManagedObjectContext (MOC) you can’t tell (in the normal course of its use) whether it’s a fault or a realized object”. A fault will be converted into a realized object (“fired”) automatically by the Core Data framework in most cases when it is necessary to do so,

For example:- when accessing a property of the object. If you need to fire a fault yourself, you can do so by invoking its willAccessValueForKey: method with a nil argument.

♥♥️♥️When you retrieve an object from an NSManagedObjectContext (MOC) you can’t tell (in the normal course of its use) whether it’s a fault or a realized object*** — Yes we can, use –isFault

22. What is NSManagedObjectModel?

❍ it contains information about the models or entities of the object graph, what attributes they have, and how they relate to one another.

❍ The NSManagedObjectModel object knows about the data model by loading one or more data model files during its initialization.

23. What is an Attribute?

An attribute is a piece of information attached to a particular entity. For example, an Employee entity could have attributes for the employee’s name, position and salary. In a database, an attribute corresponds to a particular field in a table.

24. What is the relationship?

A relationship is a link between multiple entities. In Core Data, relationships between two entities are called to-one relationships, while those between one and many entities are called to-many relationships.

For example:- a Manager can have a to-many relationship with a set of employees, whereas an individual Employee will usually have a to-one relationship with his manager.

25. What is NSManagedObject?

An NSManagedObject is a run-time representation of a Core Data entity. You can read and write to its attributes using Key-Value Coding.

26. What is Concurrency?

Concurrency is the ability to work with the data on more than one queue at the same time. If you choose to use concurrency with Core Data, you also need to consider the application environment.

For the most part, AppKit and UIKit are not thread-safe. In macOS in particular, Cocoa bindings and controllers are not threadsafe — if you are using these technologies, multithreading may be complex.

There are two concurrency types a managed object context can use:-

🌲 Private Queue Concurrency

🌲 Main Queue Concurrency

27. What is Private Queue Concurrency?

Private 🗝 Queue specifies the context that will be associated with a private dispatch queue instead of the main queue. This is the type of queue you just used to move the export operation off of the main queue so it would no longer interfere with the UI.

28. What is Main Queue Concurrency?

Main Queue, the default type, specifies that the context will be associated with the main queue. This type is what the main context (core data stack.mainContext) uses. Any UI operation, such as creating the fetched results controller for the table view, must use a context of this type.

Contexts and their managed objects must only be accessed from the correct queue. NSManagedObjectContext has perform(_:) and performAndWait(_:) to direct work to the correct queue.

29. What is Wrappers?

Wrapper libraries provide some much needed syntactic sugar and convenience methods to Core Data’s verbose and complicated APIs.

For example:- to insert a new managed object into a managed object context, it’s a class method.

30. What are Synchronizers in Core data?

Whereas adapters synchronize information through an existing, general-purpose interface such as REST, synchronizers use a more direct protocol, offering better integration and performance at the expense of portability and generality.

31. Clean way to save observers on Core Data objects?

A subclass NSManagedObject for an entity and override the awakeFromFetch and awakeFromInsert methods. the awakeFromInsert gets called when you first insert the entity, so you could move your existing code to add the observers to there. The awakeFromFetch is where you would add the observers when fetching.

32. What is the difference between transformable and binary data?

With a transformable attribute, you read and write instances of any class that can be converted to and from NSData. The actual data storage is the same as with a binary attribute, but Core Data uses an NSValueTransformer to convert to/from NSData when necessary.

For example:- say your managed object has an image attribute where it would be convenient to read and write UIImage directly. Except, UIImage can’t be saved in Core Data. But UIImage can be converted to and from NSData. So, if you used a transformable attribute you could read and write UIImage while still keeping NSData in the data store.

33. How can I encrypt Core-Data contents on an iPhone?

You can encrypt individual properties in your Core Data model entities by making them transformable properties, then creating an NSValueTransformer subclass which will encrypt and decrypt the data for that property. While this is not the whole-database decryption that you’re looking for, it will have a much lower memory footprint than decrypting an entire database into memory. Additionally, it will allow the decryption to be done lazily, rather than all upfront, so your application will load much faster. Depending on the encryption used, I would even expect that the on-disk data accesses for loading each entity would be slower than the decryption process for the properties, so you won’t see that much of a performance penalty when accessing the properties.

Transformable properties like this are very easy to use because you read and write to them as normal, while the encryption/decryption goes on behind the scenes.

34. How to Save custom class into Core data?

You have a couple of options:

👉🏻 Don’t tell Core Data how to transform the data. In this case, Core Data will attempt to call encodeWithCoder: on your object to convert it to NSData. That’s why you get the error that mentions this method — it’s trying to call the method on your class, but that method doesn’t exist. In this case, your class must conform to NSCoding for the transformation to occur.

👉🏻 Tell Core Data on how to transform the data. In this case you create a subclass of NSValueTransformer that performs the transformation. You configure this on the attribute, either in the Core Data model editor or in code. In this case, you must have a custom transformer class that knows how to perform the transformation.

35. What is transformable in core data?

Transformable attributes are useful for storing non standard object types within Core Data.

For Example:- I provide code Below that lets you store UIImages as An Attribute within core data. The image Data is Converted to and From an NSData Instance that contains the image’s PNG Representation .this is all handled transparently for you by a custom NSValueTransformer.

36 What is Uniquing?

Core Data ensures that — in a given managed object context — an entry in a persistent store is associated with only one managed object. The technique is known as Uniquing. Without uniquing, you might end up with a context maintaining more than one object to represent a given record.

37. What is an Entity?

A Managed object model allows core data to map from records in a persistent store to managed objects that you use in your Application. The model is a collection of entity description objects(instance of NSEntityDescription).

38. How to synchronize contexts?

The Core Data framework uses notifications to notify objects of changes taking place in a managed object context. Every managed object context posts three types of notifications to notify objects about the changes taking place in the managed object context:

🌴 NSManagedObjectContextObjectsDidChangeNotification

🌴 NSManagedObjectContextWillSaveNotification

🌴 NSManagedObjectContextDidSaveNotification

☄️ Managed Object Context Did Change

The NSManagedObjectContextObjectsDidChangeNotification notification is broadcast every time a managed object in the managed object context changes. Every time a managed object is inserted, updated, or deleted from a managed object context, the managed object context posts an NSManagedObjectContextObjectsDidChangeNotification notification.

☄️ Managed Object Context Will Save

As the name of the NSManagedObjectContextWillSaveNotification notification suggests, this notification is posted before a save operation is performed.

☄️Managed Object Context Did Save

The managed object context performing the save operation posts an NSManagedObjectContextDidSaveNotification notification after successfully saving its changes.

39. what is the Difference between core data and SQLite?

SQLite:

🌿 SQLite is database itself like we have SQL Server.

🌿 Have Data Constraints features.

🌿 Operates on data, store in Disk.

🌿 Can Drop table and Edit data Without loading them in memory.

🌿 Slow as Compared to core data.

CoreData:

🌱 core data is ORM(Object graph model) which create a layer between the database and the UI. It speeds up the process of interaction as we don’t have to Write Queries, just work with ORM and let ORM handled the backend. For save or retrieval of large data because of it’s abilities to handle the less processing speed of the device.

🌱 Don’t have Data Constraints if required need to implement by business logic.

🌱 Operates on in memory(data needs to be loaded from disk to memory)

🌱 Need to load entire data if we need update drop table.

40. What is Transient Property?

Transient properties are properties on an NSManagedObject that are not persisted t the object-store. They are calculated at runtime, usually on the basis of other property Values.

Thank You!

I hope you will like this. 😊 😊 😊 😊😊 Thanks for reading. 🎉🎉🎉🎉

If you having any query regarding this tutorial ? or want to know something more about it. get me on:- @Ravindra Bhati

--

--

Ravindra Bhati

Software Engineer, I’m mobile application developer proficient with programming languages SwiftUI, Swift and Objective-C, Unit testing, Accessibility