Reputation: 45921
I'm developing an iOS 4 app with latest SDK and XCode 4.2.
I have a question about delegates and how to assign/release objects to them.
My code is:
#import <Foundation/Foundation.h>
#import "SBJson.h"
#import "WebServiceDelegate.h"
@interface UserWebService : NSObject
{
SBJsonParser* parser;
NSURLRequest* request;
NSMutableData* receivedData;
NSInteger response;
id<WebServiceDelegate> delegate;
}
@property (nonatomic, readonly) NSInteger response;
- (id)initWithDelegate:(id<WebServiceDelegate>)del;
And its implementation:
#import "UserWebService.h"
@implementation UserWebService
@synthesize response;
- (id)initWithDelegate:(id<WebServiceDelegate>)del
{
if (self = [super init])
{
delegate = [del retain];
parser = [[SBJsonParser alloc] init];
}
return self;
}
-(void)dealloc
{
[parser release];
[request release];
[receivedData release];
[super dealloc];
}
Is this correct?
delegate = [del retain];
And, Have I to release del
at dealloc?
If I use
delegate = del;
instead of
delegate = [del retain];
I get a EXC_BAD_ACCESS on object dealloc.
In a nutshell, I'm not sure if I'm assign and releasing del
object correctly.
Upvotes: 0
Views: 680
Reputation: 104
You need to assign the delegate value like this
@interface UserWebService : NSObject
{
SBJsonParser* parser;
NSURLRequest* request;
NSMutableData* receivedData;
NSInteger response;
id<WebServiceDelegate> delegate;
}
@property (nonatomic, assign) id<WebServiceDelegate> delegate;
@property (nonatomic, readonly) NSInteger response;
- (id)initWithDelegate:(id<WebServiceDelegate>)del;
@implementation UserWebService
@synthesize response;
- (id)initWithDelegate:(id<WebServiceDelegate>)del
{
if (self = [super init])
{
delegate = del;
parser = [[SBJsonParser alloc] init];
}
return self;
}
So in that case you do not need to release the delegate
Upvotes: 0
Reputation: 8147
When you're using delegates, your object should not retain & release it since it does not own it.
Implement the accessor methods. In a memory-managed program, to avoid retain cycles, the setter method should not retain or copy your delegate.
- (id)delegate {
return delegate;
}
- (void)setDelegate:(id)newDelegate {
delegate = newDelegate;
}
Upvotes: 1