Objective-C Memory Question

后端 未结 6 643
感动是毒
感动是毒 2021-01-23 07:45

Is it a leak if I have a view controller and allocate the view like this:

self.view = [[UIView alloc] initWithFrame:frame];

Do I need to do som

6条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-23 08:16

    Yes, it's a leak. Your solution is correct, or you can do:

    view = [[UIView alloc] initWithFrame:frame];
    

    Where view is an instance variable. But it's not such good practice. As commented below, in a UIViewController view is a superclass property, so my code example is doubly wrong. However, the principle that self.variable is invoking setVariable:, and will observe the retain style of the property declaration is worth noting. In such cases you can directly assign to the instance variable above, which omits the retain - and makes such code a horror to maintain, which explains why Apple's Objective C 2.0 property syntactic sugar isn't universally admired.

    Corrected because Georg was entirely correct.

提交回复
热议问题