Leopard Properties and NSMutable Array
Jonathan Dann
j.p.dann at gmail.com
Sun Jan 6 09:57:17 PST 2008
On 6 Jan 2008, at 03:43, Bill Bumgarner wrote:
> On Jan 5, 2008, at 7:10 PM, André Pang wrote:
>> On 06/01/2008, at 12:53 PM, Bill Bumgarner wrote:
>>> Which, unfortunately, is the alternative. There is an
>>> enhancement request already to offer a mutablecopy keyword.
>> Is there actually a use for a 'mutablecopy' keyword? I ran into
>> the same problem as Jonathan, but then realised that retain
>> semantics are typically what you want for a mutable object. I
>> can't quite think of a case where a mutable copy of the array in
>> the class would actually be useful.
>>
>> (Maybe that thought can be used as a possible warning: if you
>> define a property for a type that obeys the NSMutableCopying
>> protocol, perhaps a warning can be emitted if you use copy rather
>> than retain...)
>
> There are uses for mutablecopy in that there has been more than one
> person that has filed a request for it. :)
>
> Seriously, though, there are cases where mutablecopy makes a lot of
> sense. Specifically, if your object model is such that your object
> wants to take ownership of the contents of the array and changes
> therein. It is much easier to guarantee that a mutable array's
> contents haven't changed if you have isolated ownership of said
> mutable array; copying on set and returning a copy on get.
>
> Of course, that has efficiency / performance / memory implications
> and, thus, balance must be maintained between performance and bullet
> proof.
>
> b.bum
>
What I really wanted was the ability to declare the mutable array as a
property as a I've really grown to like the 'dot syntax'. So here is
the solution that seems to have worked:
@interface Foo : NSObject {
NSMutableArray *array;
}
@property(copy) NSMutableArray *array;
- (void)setArray:(NSMutableArray *)a;
- (NSMutableArray *)array;
@end
@implementation
@dynamic array;
- (void)setArray:(NSMutableArray *)a;
{
if (array != a) {
[array release];
array = [a mutableCopy];
}
}
- (NSMutableArray *)array;
{
[return array];
}
@end
In my main.m I can then call [array addObject:[NSString string]];
without an error or compiler warnings.
I think I could pass the setter an NSArray too as NSArray conforms to
NSMutableCopying. Is there anything that I missed, could this go
horribly wrong somewhere?
Jon
More information about the MacOSX-dev
mailing list