Home

NSCopying

NSCopying is a protocol in the Foundation framework that defines a standard interface for creating copies of objects. An object that conforms to NSCopying provides an implementation of the method copyWithZone:, which is called when the object is copied (for example, via the copy message). The protocol is commonly adopted by classes whose instances are intended to be duplicated, such as mutable data containers and model objects.

Copying semantics: The copy operation may perform a shallow or deep copy depending on the class. A

Implementation: In Objective-C, a class that conforms to NSCopying implements -copyWithZone:, typically allocating a new instance

Related protocols: NSMutableCopying declares -mutableCopyWithZone: so a class can provide a separate mutable copy. The zone

Notes: Copying is distinct from archiving or encoding; it is meant for duplicating an object's in-memory state.

shallow
copy
duplicates
the
object's
immediate
values,
while
a
deep
copy
duplicates
the
entire
object
graph.
If
an
object
is
immutable,
the
copy
may
be
implemented
by
returning
self
to
avoid
unnecessary
allocation.
If
mutation
is
possible,
the
copy
should
produce
a
distinct
instance
with
the
same
initial
state
so
that
subsequent
mutations
on
the
copy
do
not
affect
the
original.
of
the
class,
copying
the
relevant
state,
and
returning
it.
Some
immutable
objects
return
self.
In
Swift,
a
class
adopts
NSCopying
and
implements
func
copy(with
zone:
NSZone?
=
nil)
->
Any.
argument
is
largely
historical
and
often
ignored
in
modern
implementations.
Developers
should
document
whether
their
copies
are
shallow
or
deep
and
ensure
thread-safety
if
copies
are
accessed
concurrently.