3

I have a class that send delegate messages to another class. If the other class is not listening, the app is crash . I was looking for a way to check if the other class is listen before i send the message.

so in the class that post the delegate , i have this condition the check that :

       if ([self.delegate respondsToSelector:@selector(NewDataFromSocketWithString:WithCommand:)])
           [self.delegate NewDataFromSocketWithString:final WithCommand:c];

Where somehow , the condition is always true, even if the class that gets the delegate is already released and not exist anymore .

How do i check the delegate before posting to eliminate crashes ?

Curnelious
  • 1
  • 16
  • 76
  • 150
  • Your problem appears to be that you are using a bogus delegate pointer, not that the delegate doesn't "respond". You need to either assure that the delegate object is retained, or assure that the pointer will be set nill if the object is destroyed. – Hot Licks May 03 '13 at 15:46

1 Answers1

5

even if the class that gets the delegate is already released and not exist anymore .

...have you tested that this is the case? If you aren't weak referencing your delegate then this won't be happening. If the delegate has actually been released then self.delegate should return nil, which would mean your if statement would evaluate to false.

The fact your if statement is evaluating to true suggests to me that your delegate is still set. Are you using ARC or manually managing memory? If it's the latter, you'll want your property to be set to assign - if it's the former, you'll want to set your delegate to weak.

lxt
  • 31,146
  • 5
  • 78
  • 83
  • I dont use ARC , the only thing i do where i want to listen to the messages is : socketInstance.delegate=self; in the relevant class. later on , this class is replaced(its a main view). there is something else that i should do to the delegate itself to release it ? – Curnelious May 03 '13 at 15:53
  • 2
    @Rant You should be using ARC. But, if not, then you need to manually set the delegate to `nil` when the delegate object is released. `weak` under ARC fixes that. If you make the `delegate` a `retain` property, then you'll likely have a retain cycle. – bbum May 03 '13 at 16:19
  • Using ARC in 2013 is a pretty good idea, I guess, why not use it? – Sergey Grischyov May 03 '13 at 19:28
  • @SergiusGee you right but i use Xcode for 2 years without it, and today i just afraid to learn all of its rules ,so i have just steak to non-arc . – Curnelious May 05 '13 at 09:36
  • I know this is an old thread, but that's like saying I'm used to my iPhone 1, I won't bother with 2,3,4,5 and the upcoming six. Always get with the times! – Rambatino May 18 '14 at 20:58