数组的内存泄漏 - Objective C
我在尝试消除代码中的内存泄漏时遇到了一些麻烦。在下面的代码中,我在“configurationArray = [[NSArray arrayWithContentsOfFile:controllerConfigurationFilePath] keep];”行上出现内存泄漏但是,当我删除保留时,应用程序崩溃,并且将保留更改为自动释放也会导致崩溃。
谢谢, 威廉
-(NSArray*)decodeConfigurationFile:(NSString*)fileName{
NSArray* configurationArray = [[NSArray alloc] init];
NSString *controllerConfigurationFilePath = [[NSBundle mainBundle] pathForResource:fileName ofType:@"plist"];
if (controllerConfigurationFilePath != nil) {
// returns array of items storing the data for form
configurationArray = [[NSArray arrayWithContentsOfFile:controllerConfigurationFilePath] retain];
}
// returns fields dictionary objects from plist into an array
return [[configurationArray objectAtIndex:0] objectForKey:@"fields"];
}
am having some trouble with attempting to remove a memory leak from my code. In the code below, I get a memory leak on the line "configurationArray = [[NSArray arrayWithContentsOfFile:controllerConfigurationFilePath] retain];" however when I remove the retain, the application crashes and changing the retain to an autorelease also causes a crash.
thanks,
William
-(NSArray*)decodeConfigurationFile:(NSString*)fileName{
NSArray* configurationArray = [[NSArray alloc] init];
NSString *controllerConfigurationFilePath = [[NSBundle mainBundle] pathForResource:fileName ofType:@"plist"];
if (controllerConfigurationFilePath != nil) {
// returns array of items storing the data for form
configurationArray = [[NSArray arrayWithContentsOfFile:controllerConfigurationFilePath] retain];
}
// returns fields dictionary objects from plist into an array
return [[configurationArray objectAtIndex:0] objectForKey:@"fields"];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题似乎是您通过 do 分配一个数组
,然后通过 do 创建一个新数组,
而没有释放您创建的第一个数组。第一行应该只是
And 你不应该需要保留,因为它是一个局部变量,并且你不会在该函数的范围之外保留指向该数组的指针。
崩溃可能是由于调用此方法的对象可能没有保留此方法返回的对象,如果没有其他东西保留它,该对象将与数组一起释放。因此,当您尝试在代码中的其他位置访问该对象时,该对象不再存在。
如果调用对象需要保留这个返回的对象,则调用对象应该保留这个返回的对象。
The problem seems to be that you're allocating an array by doing
and then you're creating a new array by doing
without ever releasing the first array you created. The first line should be just
And you shouldn't need the retain, since it's a local variable and you are not keeping a pointer to that array beyond the scope of that function.
The crash probably comes from the fact that the object calling this method is probably not retaining the object returned by this method, which will be deallocated along with the array if nothing else is retaining it. So when you're trying to access that object somewhere else in your code, the object is no longer there.
If the calling object needs to keep this returned object, the calling object should retain the returned object.