Memory leak problem and i need help #1

前端 未结 5 710
北海茫月
北海茫月 2021-01-23 08:34

I am very new at this and seems to have a leak in this piece of code that i cannot fix:

The Instruments shows on this line with a 100%:

NSMutableA

5条回答
  •  旧时难觅i
    2021-01-23 08:46

    Since I believe the code from picciano will fix the issue of the openingsposter, here a small explanation why it should fix the issue.

    If you give a property the retain attribute, it will create an accessor method that looks somewhat like this (simplified):

    @property (nonatomic, retain) NSValue *value;
    
    - (void)setValue:(NSValue *)aValue {
        value = [aValue retain];
    }
    

    Only when the retainCount reaches 0 an object is released, using retain, alloc and copy increases the retainCount. Remember: only when using the accessor method the retain actually happens (besides using alloc, retain and copy directly). The accessor method is usually called when using one of the following methods:

    // the 2 most obvious ways to call the accessor methods ...
    object.value = someValue;
    [object setValue:someValue];
    

    You created a retain property in your code, yet you didn't use the accessor method, so the object was never retained.

    // no accessor used here ...
    managedObjectContext = [(FamQuiz_R0_1AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
    

    If you would release it from this point on, it would cause a crash, since the retainCount would actually become -1 at some point (since it never got to 1 in the first place). Therefore you should set the property like this:

    // the dot-notation syntax to make use of the accessor method ...
    self.managedObjectContext = [(FamQuiz_R0_1AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
    

    or (in my opinion preferably):

    // making use of the accessor method directly, which is very unambiguous ...
    NSManagedObjectContext *context = [(FamQuiz_R0_1AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
    [self setManagedObjectContext:context];
    

    This way you can be sure the retain actually happens.

    The second notation to accessor setters is in my opinion superior and I consider it good habit to use it for setting properties whenever possible. Read more about people who share this opinion and their reasoning on the following sites:

    • Cocoa Is My Girlfriend
    • The Big Nerd Ranch

提交回复
热议问题