Recent study objective-c, I found that if you create a project using ARC, very easy to memory leaks, often an object has been freed me still in use, because do not quite understand this mechanism, and now I give two examples, Please help me analyze the experience.
Example 1: In the beginning, AppDelegate.m method that starts when written like this:
- (BOOL) application: (UIApplication *) application didFinishLaunchingWithOptions: (NSDictionary *) launchOptions
{
self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
/ / Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
/ /
UITabBarController tabBarController = [[UITabBarController alloc] init];
[TabBarController setViewControllers: [self showConnectViewOnWindow]];
[TabBarController setDelegate: self];
/ /
[[Self window] addSubview: [tabBarController view]];
[Self.window makeKeyAndVisible];
return YES;
}
Then I also did other jobs: tabBarController have tabBarItem, click invokes a method
But every time a click, it will report unrecognized selector send to instance error,
Later, check the Internet, saying it was put tabBarController defined as global variables, otherwise this method one end, tabBarController was freed, so click on the object generation time is gone, so I define it as a global variable, can indeed But my question is, why he would approach an end freed you, [[self window] addSubview: [tabBarController view]]; my one not already reference it in the self window yet, how could he be released, java and C # I think this situation is not released inside out.
Example 2: In viewdidload method inside:
[Self.navigationItem setTitle: Title];
leftButton = [[UIBarButtonItem alloc] initWithTitle: Cancel
style: UIBarButtonItemStyleBordered
target: self
action: @ selector (CancleButtonClicked)];
self.navigationItem.leftBarButtonItem = leftButton;
Here I give the navigation bar above the screen plus a left button, then click on this button will use methods CancleButtonClicked to respond, but I'm up and running with a click, or reported unrecognized selector send to instances wrong, here is what object release a, leftButton do? But self.navigationItem.leftBarButtonItem = leftButton already cited ah.
Please express their opinions, thank you.
Reply:
Examples of a [[self window] addSubview: [tabBarController view]];
You just cited tabBarController of view, does not refer to tabBarController
Example 2, do not know why, to see if there is not misspelled it.
Also, I feel local variables memory is generally only effective within its life cycle. Out of the area defined by it, if not released, it is best not to use it. A personal opinion.
Reply:
Ah, these days do a little more able to avoid this problem.
No comments:
Post a Comment