I know that this is the wrong way to do it, but could someone explain
why this causes a memory leak?  The crux of it is, you set an ivar to
be Mutable, and you set the property to return an immutable object.
You override the default accessor method to return a copy of the
mutable ivar.

@interface MyObject:NSObject{
  NSMutableArray * collection;
}
@property(nonatomic, readonly)NSArray * collection;
@end


@implementation MyObject
-(void)dealloc{
    [collection release];
    [super dealloc];
}

-(id)init{
    if(self = [super init])
    {
        collection = [[NSMutableArray alloc] init];
    }
}

-(NSArray *)collection{
    return [collection copy];
}
// additional code that populates the collection.
@end

Again, it's probably not the most efficient, to constantly return a
copy of an object, especially if the property is accessed repeatedly.
This is more of a curiosity I noticed the other day.  If I run
Instruments, and I allocate MyObject, and release it later, the Leaks
instrument will throw up a leak on NSCFArray, any any objects it might
contain (in this case it's referring to the iVar 'collection').  I
didn't think the runtime did anything with properties other than
create the accessor methods, and the developer was solely responsible
for handling the memory and/or overriding the implementation but
apparently the runtime wants to do something with them?  If I override
the default getter for the @property I get the same behavior(leak on
NSCFArray and it's objects) with:

@property(nonatomic, readonly, getter=getCollection)NSArray * collection;

-(NSArray *)getCollection{ return [collection copy]; }

Again, I can see why this is a bad idea, but I was just more curious
to know what's actually going on in the background that makes it a bad
idea.
_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

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:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to