gpt4 book ai didi

ios - 在重用之前释放并在退出时解除分配的对象的潜在泄漏

转载 作者:行者123 更新时间:2023-11-28 18:11:50 26 4
gpt4 key购买 nike

使用 xcode 分析器,我收到了一个对象可能泄漏的警告。这个警告令人费解,我需要一些解释为什么我会收到这个错误。以下是 mediaSources 保存指向相关对象指针的代码:

在 .h 文件中,创建了一个指向 MediaSources 类的指针并赋予了一个保留属性:

@interface RootViewController : UIViewController <...>
{
...

MediaSources *mediaSources;

...
}

@property (nonatomic, retain) MediaSources *mediaSources;

.m文件中(rootViewController)是一个可以多次调用的方法。因此,我在每个条目上释放对象并分配一个新对象。 MediaSources 对象执行后台任务,所以我不想在知道它完成之前释放它。如果我在分配该类的行上使用 autoRelease,它就会崩溃。 :

-(void) getSelectedMediaSources
{
[self setMediaSources: nil]; // release old stuff and nilify
[self setMediaSources: [[MediaSources alloc] init]];
[self.mediaSources checkForMediaSourceUpdates];
}

同样在.m文件中,mediaSources也被合成,并在dealloc中释放

@synthesize mediaSources;

...

- (void)dealloc {
...
[mediaSources release];
...

[super dealloc];
}

请解释为什么我会收到此警告。我不明白怎么会有泄漏。 Dealloc 应该释放这个对象的最后一个副本。

响应来自 checkForMediaSourceUpdates 的代码请求。这会变得有点复杂,但下面是本质:

(void) checkForMediaSourceUpdates
{
NSString *s = [NSString stringWithFormat:@"http://www.mywebsite.com/mediaSources/%@/mediaSources.plist", countryCode];

NSURL *url = [NSURL URLWithString:s];
NSURLRequest *req = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:60.0];
MyDownloader *d = [[MyDownloader alloc] initWithRequest:req];
[self.connections addObject:d];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkForMediaSourceUpdatesDownloadFinished:) name:@"connectionFinished" object:d];
[d.connection start];
[d release];
}

-(void) checkForMediaSourceUpdatesDownloadFinished: (NSNotification *) n
{
MyDownloader *d = [n object];
NSData *data = nil;
if ([n userInfo]) {
NSLog(@"In checkForMediaSourceUpdatesDownloadFinished: MyDownloader returned an error");
}
else {
data = [d receivedData];

// do something with the data
}
}

myDownloader 类执行输入 NSURLRequest 中指定的文件下载。下载完成后,该类会生成一个名为“connectionFinished”的NSNotification。此类的用户必须注册此通知并处理此类的所有清理操作。如果下载失败,该类将生成一个 NSNotification,也称为“connectionFinished”,但会添加一个 userInfo 指示发生了错误。同样,此类的用户必须注册此通知并处理此类的所有清理操作。

最佳答案

根据定义,您将一个自动释放的对象传递给一个合成的 setter。 setter 本身保留对象,因此以下行是错误的:

[self setMediaSources: [[MediaSources alloc] init]]; 

应该是:

[self setMediaSources: [[[MediaSources alloc] init] autorelease]]; 

此外,您之前不需要使用 nil 调用您的 setter。通过 setter 设置不同的对象时,旧对象将被释放。合成的 setter 看起来像这样:

- (void) setMediaSources:(MediaSources *)mediaSources {
if (_mediaSources != mediaSources) {
[_mediaSources release];
_mediaSources = [mediaSources retain];
}
}

问题是:为什么每次调用 getSelectedMediaSources 时都需要分配一个新的 MediaSource?在解除分配自动释放的 MediaSource 时,您预计会发生什么崩溃?您是将其设置为另一个对象的委托(delegate)还是将其注册到 NSNotificationCenter?如果是这样,请不要忘记取消委托(delegate)或将其从通知中心移除。

关于ios - 在重用之前释放并在退出时解除分配的对象的潜在泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16677106/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com