0

In my app delegate I have one object that I need to use in some different 3 viewControllers. To use it I do in the interface

NewsPadAppDelegateiPad *delegate;

and in the implementation I do

delegate = (NewsPadAppDelegateiPad *)[[UIApplication sharedApplication] delegate];
[delegate.reader setDelegate:self];
....
[delegate.reader doSomthing];

When In my dealloc method I do

[delegate release];
delegate=nil;

I receive the error

[CFString release]: message sent to deallocated instance 0x9d4fac0

I really need to release that?

Usi Usi
  • 2,967
  • 5
  • 38
  • 69
  • You should not retain and release your app delegate. It's created by the application and will persist to the end of the application without your help. In fact, there is no real need to have your `delegate` variable in your view controllers -- you can re-fetch the delegate pointer whenever you need it, maybe keeping it in a local variable in a given method, but not in any instance variable. – Hot Licks Aug 05 '13 at 01:36

2 Answers2

1

In general, you should not retain your delegates: this lets you avoid retain cycles - situations when two or more objects retain each other in a cycle, preventing the whole group from being deallocated.

This looks to be a pre-ARC code, so you should simply avoid retaining and releasing your delegate.

In ARC code you should declare your delegates __weak unless you have specific reasons to use strong references (specifically, you retain your delegate when you want to own the delegating object; this is very rare - in fact, it's usually the other way around).

Here is a good discussion of the topic on why delegates are not usually retained.

Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Note that this specific case is the "app delegate", which is created by UIApplication when the app starts and persists to the end. It is, in effect, a "singleton". – Hot Licks Aug 05 '13 at 01:40
  • @HotLicks I think that [another exception is `CAAnimation`](http://developer.apple.com/library/ios/#DOCUMENTATION/GraphicsImaging/Reference/CAAnimation_class/Introduction/Introduction.html) and modal delegates. – Sergey Kalinichenko Aug 05 '13 at 01:56
0

According to Cocoa's memory management name convention, you don't own the object so you don't release it. It will be released for you when it goes out of scope.

Daniel Martín
  • 7,815
  • 1
  • 29
  • 34
  • Does my code create a new instance of my delegate or it is just a pointer? I don't want to waste memory ;) – Usi Usi Aug 04 '13 at 23:57