Should I call release on an autorelease object assigned to a retained property before reassigning it?

StackOverflow https://stackoverflow.com/questions/19440304

On still not %100 clear on this. When the AVPlayer connection breaks, the only way to restart it reliably is to recreate the objects. As they are created with convenience methods they are autoreleased but the property setter should retain them. Should I be releasing them before reassigning them? When I did I was getting random exceptions. Without the release it doesn't crash but I'm pretty sure thats a leak???

@interface
@property (retain, nonatomic) AVPlayerItem *streamItem;
@property (retain, nonatomic) AVPlayer *streamPlayer;

@implementation

- (void)restartStream
{
    //[self.streamItem release]; // ???????
    //[self.streamPlayer release]; // ???????
    self.streamItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:@"http://someStream.com"]];
    self.streamPlayer = [AVPlayer playerWithPlayerItem:self.streamItem];
}
有帮助吗?

解决方案

Your setter should release the old value before assigning and retaining the new value. See this answer on how synthesized MRC are implemented. If you are not providing your own setter, this should not leak memory.

- (void)restartStream
{
    self.streamItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:@"http://someStream.com"]];
    self.streamPlayer = [AVPlayer playerWithPlayerItem:self.streamItem];
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top