aryaxt
aryaxt

Reputation: 77596

Objective C - delegation question?

I need to create a class that gets a delegate does some calculation and then calls the delegate.

Upvotes: 0

Views: 305

Answers (3)

aryaxt
aryaxt

Reputation: 77596

The following worked for me, I simply pass the object to my delegate method and i release it there. This is exactly how NSUrlConnection and some other Classes work, so I think it's the correct way of doing it.

-(void)viewDidLoad 
{ 
     MyClass *class = [[MyClass alloc] initWithDelegate:self]; 
}

-(void) MyClassRespond :(MyClass*)myClass 
{ 
     NSData *myData = myClass.data;
     [myClass release];
}

Upvotes: 0

jer
jer

Reputation: 20236

Let's assume for the moment that your delegate is an instance of Foo and the object calling the delegate is MyClass. Your delegate property on MyClass should look something like this:

@property (assign) id delegate;

of course, you're likely going to want delegate to conform to a protocol of some sort, so use the id<...> syntax as you desire. delegates should always be assign. You can get into some weird cyclic problems if you retain, that you're going to want to avoid. Therefore, you release where appropriate. i.e., wherever you'd release that Foo instance anyway. Ideally, here you're releasing the MyClass instance in your Foo dealloc method anyway, so you're not leaking, and there's no object left around to call the delegate.

Upvotes: 1

Aurojit Panda
Aurojit Panda

Reputation: 909

The class can't destroy itself, and you can't init a class object without allocating it (one of the issues being where exactly do the fields get stored without some stuff.

I am not sure why it needs to destroy itself, but the usual method to do this would be to have a variable of type MyClass* _class in the class with the viewDidLoad method. You would then do the equivalent of

-(void)viewDidLoad { _class = [[MyClass alloc] initWithDelegate:self]; }

-(void) MyClassRespond :(NSData*)data { 
      [_class release];
      //use data and populate on screen }

You could of course also do something where you pass MyClass back to the delegate method, so something like

-(void)viewDidLoad {MyClass *class = [[MyClass alloc] initWithDelegate:self]; }

-(void) MyClassRespond :(NSData*)data fromClass: (MyClass*)class { 
      [class release];
      //use data and populate on screen }

In this case your delegate would call MyClassResponds as

[delegate MyClassRespond:data fromClass:self];

It might also make sense to try and make MyClass reusable so you don't need to dispose it quite as quickly, but I understand there are cases where this doesn't work.

Upvotes: 1

Related Questions