Objective-C Memory Question

后端 未结 6 629
感动是毒
感动是毒 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:09

    You need to read the Cocoa Memory Management Rules.

    You obtained the object with +alloc. Therefore, according to the rules, you are responsible for releasing it. Your own solution is perfectly fine, or you could do:

    self.view = [[[UIView alloc] initWithFrame:frame] autorelease];
    
    0 讨论(0)
  • 2021-01-23 08:15

    This depends on the declaration of the view property. If it's not a (retain) property, then you're fine. If it is a retaining property, you must call release.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-23 08:18

    There is a very simple rule for Objective-C memory management. If you've sent retain message, you've to send release also. I do not know exceptions with this rule is SDK itself.

    Here we've alloc, that sends retain itself (always), so you have to release object somewhere. You can do it in dealloc or right here, after assigning it to self.view.

    0 讨论(0)
  • 2021-01-23 08:25

    In objective c, we need to maintain retain count of an object as zero after its purpose. So here in your code you must release the object. Then it will not create any leakage problems.

    The second one you specified is the right way. It is not a compulsory , it is the way to express how effective our code is.

    0 讨论(0)
  • 2021-01-23 08:34

    Yes, the second one. Properties (self.view) retain their value usually.

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