Single, global, object instance
I've been slowly churning through my first iPhone app, outside of learning within the context of a book. What I would like to have is a single, global variable that tracks whether or not there is a person logged into the application. In the past with C++, what I've done is declared a variable in my "main" function file and then re-declared it in my other files as extern. I've tried this with Objective-C, but I'm running into memory management issues when debugging with Leaks. Here is the code I'm trying to use.
main file
#import "clsPerson.h"
clsPerson *LoggedInPerson = nil;
int main(int argc, char *argv[]) {
//...main code...
}
[App]_Prefix.pch* - Prefix file
...
#import "clsPerson.h"
extern clsPerson *LoggedInPerson;
...
Login code - Login View Controller (Modal popup on top of Root)
I should mention here also, that it currently checks to see if the variable is nil. If it is, then it forces you to login. In order to use nil, I believe I have to alloc and dealloc rather than reusing the same memory address?
...
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];
...
Logout code - Root View Controller
...
- (void)btnLogo开发者_如何学编程utTapped {
[LoggedInPerson dealloc]; //There is only one object, so I tried to force it to dealloc fully
LoggedInPerson = nil;
[clsPerson ClearUserInfo];
...
}
...
This seems to work fine and doesn't produce any errors, but watching the app with Leaks shows that my allocation statement is leaking memory somewhere. It typically happens if I logout, force a "low memory warning", and then login again. Are there any glaring problems here? I'm still getting my grips around memory management, but I think I'm pretty close. Thanks for any help in advance!
So, you don't need to retain the object if you've just allocated it. The retain count will already be +1.
But the other issue is you should be releasing it when the user logs out, not deallocating it. You should never call dealloc directly.
精彩评论