Stop ARC releasing an object while it is idle

前端 未结 3 803
梦如初夏
梦如初夏 2021-01-17 00:29

I am having a problem with memory management in objective C. Ive been reading through the Advanced Memory Management Programming Guide but I cannot find a solution to my pro

相关标签:
3条回答
  • 2021-01-17 00:56

    I stumbled upon this case several times when working with UITableViews. I created a private @property (strong) id *yourObjectRetain and assigned my object to it. An array for multiple objects will also work.

    0 讨论(0)
  • 2021-01-17 00:57

    Your controller is getting dealloc'ed when the detailViewController is dealloc'ed. Hence, you must move the handle of your controller and define in it the any of the following :

    1. MasterViewController or your application's RootViewController OR
    2. AppDelegate OR
    3. Create a singleton as answered by "trojanfoe"
    0 讨论(0)
  • 2021-01-17 01:21

    Use a singleton pattern so that Controller looks after its own lifetime and exists app-wide. This shared instance will exist from when it's first requested until the app terminates and ARC will not release it arbitrarily.

    Controller.h:

    @interface Controller : NSObject
    
    + (Controller *)sharedInstance;
    
    @end
    

    Controller.m:

    #import "Controller.h"
    
    static Controller *_instance = nil;
    static dispatch_once_t _onceToken = 0;
    
    @implementation Controller
    
    + (Controller *)sharedInstance {
        dispatch_once(&_onceToken, ^{
            _instance = [[Controller alloc] init];
        });
        return _instance;
    }
    
    // You could add this if you want to explicitly destroy the instance:
    + (void)destroy {
        _instance = nil;
        _onceToken = 0;
    }
    
    0 讨论(0)
提交回复
热议问题