Objective-C Memory Management: crash on release

前端 未结 5 1405
情深已故
情深已故 2021-01-29 00:07

I\'m new to Objective-C and can\'t seem to get the memory management code right. I have the following code:

Media* myMedia = [self.myMediaManager getNextMedia];
         


        
5条回答
  •  难免孤独
    2021-01-29 00:14

    This updated code is suspicious:

    Media* nextMedia = [[Media alloc] init];
    
    [self setNextMediaIndex];
    
    if (self.mediaIndex > -1)
    {
        nextMedia = [mediaArray objectAtIndex: self.mediaIndex];
    }
    

    Depending on the condition in the if() clause, you assign a new value to nextMedia, which makes the value you just allocated unreachable, i.e. it can't be released.

    Also, you don't retain the value you get from the array, so you should not release it either. But if the if() clause does not run, you still have the instance you alloc-ed, and that should be released.

    That is not good. Try:

    Media* nextMedia = [[Media alloc] init];
    [self setNextMediaIndex];
    if (self.mediaIndex > -1)
    {
        [nextMedia release];
        nextMedia = [[mediaArray objectAtIndex: self.mediaIndex] retain];
    }
    

    You could also do (and I would prefer that):

    Media *nextMedia;
    [self setNextMediaIndex];
    if (self.mediaIndex > -1)
    {
        nextMedia = [[mediaArray objectAtIndex: self.mediaIndex] retain];
    }
    else
    {
        nextMedia = [[Media alloc] init];
    }
    

    Now you can release nextMedia when that is not needed anymore, without any ambiguity about the retain count.

提交回复
热议问题