Re: Best Practice for Returning Immutable Objects?
Re: Best Practice for Returning Immutable Objects?
- Subject: Re: Best Practice for Returning Immutable Objects?
- From: email@hidden
- Date: Tue, 3 Jun 2008 17:23:16 +0100
Karl Moskowski wrote on 2008-06-03 17:16:48:
>
> On 3-Jun-08, at 12:13 PM, Mike Abdullah wrote:
>
> > Well this cast is fairly pointless as it makes no change to the data
> > at all. Returning an NSMutableData object from an NSData method is
> > perfectly legitimate as it is a subclass. So you might as well just
> > do:
> >
> > return myData;
> >
> > Really, it's up to you. You can just use the simple option of
> > returning a mutable object, or you can do either of these:
> >
> > return [NSData dataWithData:myData];
> >
> > return [[myData copy] autorelease];
>
>
> My concern is that the returned object be truly immutable. For now,
> I'm the only one using the class, but that may change in the future.
>
If it has to be 'truly' immutable, then use one of Mike's suggestions,
which will return an immutable NSData object containing the same bytes as
the bytes in the mutable object you constructed. The code you originally
posted still returns the mutable object; casting doesn't change the 'isa'
which is what tells the ObjC runtime what class the instance is. I.e.
given an NSMutableData *foo:
(NSData *)foo "is a" NSMutableData
(NSObject *)foo "is a" NSMutableData
(id) foo "is a" NSMutableData
Cheers,
Graham.
--
Graham Lee
Senior Macintosh Software Engineer, Sophos
Tel: 01235 540266 (Direct)
Web: http://www.sophos.com
Sophos - Security and Control
Sophos Plc, The Pentagon, Abingdon Science Park, Abingdon,
OX14 3YP, United Kingdom.
Company Reg No 2096520. VAT Reg No GB 348 3873 20.
_______________________________________________
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