Ad space (banner)
๐ŸŽObjective-C Lessons
Lesson 40 / 68

Shallow copies versus deep copies

This lesson covers the difference between shallow and deep copies in Objective-C, with the aim of avoiding bugs caused by unintentionally shared data.

Assigning an Objective-C object to another variable in fact copies a reference pointing at the same thing. That is a shallow copy, and changing one affects the other.

In the sample code, NSMutableDictionary *shallow = original; makes shallow point at the same dictionary instance as original. Changing it with shallow[@"city"] = @"Osaka" therefore changes what original[@"city"] displays too.

A common early stumble is the bug where "I copied it, but the original changed as well". When you want an independent copy you have to call mutableCopy or copy explicitly.

In professional work, understanding how reference types behave is unavoidable knowledge for handling Objective-C's memory correctly.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Objective-C directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)