Re: Objective-C basics - (Why NSNumber conforms to NSCopying protocol)
Re: Objective-C basics - (Why NSNumber conforms to NSCopying protocol)
- Subject: Re: Objective-C basics - (Why NSNumber conforms to NSCopying protocol)
- From: Steve Sisak <email@hidden>
- Date: Thu, 11 Aug 2016 20:16:08 -0400
This thread seems to have gone off into the weeds by way of tortured analogy. ;-)
Going back to the OP’s question
> On Aug 11, 2016, at 2:32 AM, Sasikumar JP <email@hidden> wrote:
>
> what was the reason NSNumber conforms to NSCopying protocol.
>
> NSNumber is immutable class, Making a copy of NSNumber object returns the
> same reference.
There’s a standard idiom where immutable classes frequently have mutable subclasses (which expose the mutating methods).
In this case, it’s common for the immutable (super)class to adopt NSCopying and the mutable subclass to also adopt NSMutableCopying.
This way if you want to add an object to a collection, calling -copy has the effect of freezing the current value — the immutable class can optimize this by just returning a new reference to the same object, but the caller doesn’t have to know whether the object was immutable or a mutable subclass.
> Is there any case where NSNumber returns the new object? if not, then what
> is the purpose of conformance to NSCopying protocol.
NSString/NSMutableString is probably easier to get your head around — then just understand that NSNumber repeats the pattern for consistency.
For instance, NSDictionary “copies” keys to keep them from changing (which would be bad for hopefully obvious reasons).
HTH,
-Steve
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden