使用AppDelegate的变量作为全局变量 - 关于发布/保留的问题

时间:2010-07-08 22:06:32

标签: xcode global-variables release

我在AppDelegate中创建了一个名为“myDBManager”的变量:

@interface myAppDelegate : NSObject <UIApplicationDelegate> {
   MyDBManager *myDBManager;
}
@property (nonatomic, retain)  MyDBManager *myDBManager;

@end

我在大多数其他类中使用它作为全局变量保存所有关键应用程序数据。它只创建一次,最后才消亡。例如,在AnyOtherClass

中访问myDBManager
@interface AnyOtherClass :  UITableViewController {
   MyDBManager *myDBManager;
   NSObject *otherVar;
}
@property (nonatomic,retain)   MyDBManager *myDBManager;
@property (nonatomic,retain)   NSObject *otherVar;
@end

//getting the data from "global" myDBManager and putting it into local var of AnyOtherClass
- (void)viewWillAppear:(BOOL)animated {
   //get the myDBManager global Object
   MyAppDelegate *mainDelegate = (MyAppDelegate *)[[UIApplication sharedApplication]delegate];
   myDBManager = mainDelegate.myDBManager;
   }


-  (void)dealloc {
       [otherVar release];
        //[dancesDBManager release]; DO NOT RELEASE THIS SINCE ITS USED AS A GLOBAL VARIABLE!
        [super dealloc];
        }

这是我的问题:AnyOtherClass的所有其他局部变量,例如“otherVar”必须在AnyOtherClass的dealloc方法中释放(总是 - 是吗?),在AnyOtherClass中释放myDBManager会导致应用程序出错。

所以我永远不会在我的应用程序的任何类中释放本地myDBManager变量 - 所有其他局部变量总是被释放 - 并且它工作正常。 (甚至检查retainCount)。

我是对的,类的所有局部变量都需要在该类的dealloc中释放,或者它实际上是否正常,在使用所描述的全局变量构造的情况下根本不释放这些变量? (或任何其他情况?)

非常感谢你的帮助!

2 个答案:

答案 0 :(得分:2)

当你在AnyOtherClass中引用它时,你没有保留它,因此在那时你不能释放它。您正在直接设置ivar,因此酒店的保留不起作用。如果你打电话

self.myDBManager = mainDelegate.myDBManager;

你会保留它,并且当你取消分类时必须释放它。

但是,如果它是一个全局变量,为什么不在AnyOtherClass中使用它呢?为什么不在需要数据库管理员时调用mainDelegate.myDBManager

答案 1 :(得分:2)

在您的方案中,myDBManager不是全局变量或局部变量,而是自动保留属性(标有retain)。根据{{​​3}},nonatomic,retain属性应在dealloc中明确发布。但是,如果您的属性是合成的,则您无权访问支持成员变量,因此您无法在其上调用release;您必须使用属性设置器将其设置为nil,这会将release发送到之前的值。您是否有机会在myDBManagerAnyOtherClassmyAppDelegate设置nil媒体资源?

更新:@ Don的答案实际上是正确的。你没有调用属性设置器(self.myDBManager),因此自动保留不起作用。我将留下我的答案,以便人们可以从我的错误中吸取教训。 : - )