views:

110

answers:

2

I am using a custom class as the delegate and datasource on a UITableView. I'm doing (something like) this in my viewDidLoad method:

MyClass *myObject = [[MyClass alloc] init];
tableViewOutlet.delegate = myObject;
tableViewOutlet.dataSource = myObject;

Surely I need to decrease the retain count on myObject somewhere? But calling [myObject release] here has very bad results - the delegate gets destroyed before the table has finished doing its stuff.

I have tried

MyClass *myObject = [[[MyClass alloc] init] autorelease];

but it also has terrible consequences.

Do I have a memory leak here? If so, how and when do I release the delegate safely?

+2  A: 

make myObject an instance variable by declaring it in the @interface (.h file), then call...

[myObject release];

.. in your dealloc method.

coneybeare
+2  A: 

Your interface file:

@interface SomeClass: NSObject {
    MyClass *myObject;
}
@property (nonatomic,retain) MyClass *myObject;

@end

Your implementation file:

@implementation SomeClass
@synthesize myObject;

-(void)dealloc {
    // if you want to be safe, change tableViewOutlet properties...
    // tableViewOutlet.delegate = nil;
    // tableViewOutlet.dataSource = nil;
    [myObject release]; // retain = 0
    [super dealloc];
}
...
MyClass *obj = [[MyClass alloc] init]; // retain = 1
self.myObject = obj; // retain  = 2

// NOTE: if you instead write: myObject = obj; **NO** retain msg will be sent.
// *not* what you want in this context.
tableViewOutlet.delegate = obj; // assign, so retain =2 
tableViewOutlet.dataSource = obj;  // assign, so retain = 2
[obj release]; // retain = 1
...

@end
wkw