Assigning retained object to weak property; object will be released after assignment

前端 未结 2 1848
星月不相逢
星月不相逢 2021-02-13 11:48

I used some source code :

 KGModalContainerView *containerView = 
     self.containerView = 
         [[KGModalContainerView alloc] initWithFrame:containerViewR         


        
相关标签:
2条回答
  • 2021-02-13 12:18

    I suppose your containerView property is declared with weak attribute. If you want to have a weak attribute to a property someone should have already retained it. Here's an example:

    @property (nonatomic, weak) KGModalContainerView *containerView;
    ...
    -(void)viewDidLoad {
        [super viewDidLoad];
        KGModalContainerView *myContainerView = [[KGModalContainerView alloc] initWithFrame:containerViewRect]; // This is a strong reference to that view
        [self.view addSubview:myContainerView]; //Here self.view retains myContainerView
        self.containerView = myContainerView; // Now self.containerView has weak reference to that view, but if your self.view removes this view, self.containerView will automatically go to nil.
    
     // In the end ARC will release myContainerView, but it's retained by self.view and weak referenced by self.containerView
    }
    
    0 讨论(0)
  • 2021-02-13 12:19

    My 2 cents as a beginner in Objective C:

    The right hand side of the line that gives the warning,

    [[KGModalContainerView alloc] initWithFrame:containerViewRect]
    

    creates an object in the heap and at this point this object is not referenced by any pointer. Then this object is assigned to self.containerView. Because self.myContainerView is weak, the assignment does not increase the reference count of the object created on the right hand side. So when the assignment is done, the reference count of the object is still 0, and hence ARC immediately releases the object.

    0 讨论(0)
提交回复
热议问题