代码之家  ›  专栏  ›  技术社区  ›  jocull

单个全局对象实例

  •  0
  • jocull  · 技术社区  · 14 年前

    外部 . 我已经用Objective-C尝试过了,但是在调试泄漏时遇到了内存管理问题。这是我想用的代码。

    主要的

    #import "clsPerson.h"
    
    clsPerson *LoggedInPerson = nil;
    
    int main(int argc, char *argv[]) {
    //...main code...
    }
    

    [应用程序]_Prefix.pch* -前缀文件

    ...
    #import "clsPerson.h"
    extern clsPerson *LoggedInPerson;
    ...
    

    -登录视图控制器(根目录上的模式弹出窗口)

    我还应该在这里提到,它当前检查变量是否 . 如果是,则强制您登录。为了使用nil,我认为我必须分配和解除分配,而不是重用相同的内存地址?

    ...
    LoggedInPerson = [[clsPerson alloc] initWithJSON:(NSDictionary*)Network.JsonValues];
    [LoggedInPerson retain]; //I don't really know if this is needed?
    
    //Save this person into the default settings for next time
    [LoggedInPerson saveUserInfo];
    [[self parentViewController] dismissModalViewControllerAnimated:YES];
    ...
    

    注销代码 -根视图控制器

    ...
    - (void)btnLogoutTapped {
        [LoggedInPerson dealloc]; //There is only one object, so I tried to force it to dealloc fully
        LoggedInPerson = nil;
        [clsPerson ClearUserInfo];
        ...
    }
    ...
    

    1 回复  |  直到 14 年前
        1
  •  0
  •   Firoze Lafeer    14 年前

    所以,如果您刚刚分配了对象,就不需要保留它。保留计数已为+1。

    释放 当用户注销时,而不是释放它。你不应该直接给dealloc打电话。