我有一个示例应用程序,看起来像社交网络 iOS 应用程序。我是 cocoa 框架的新手,所以我正在研究示例代码。点击分析后,应用程序中报告了 255 个内存泄漏。我能够解决大约 100 个非常简单的泄漏,但我无法解决其余的问题。
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
//DLog(@"found this element: %@", elementName);
currentElement = [elementName copy];
if([MethodName isEqualToString:@"SignInStep"])
{
if ([elementName isEqualToString:@"item"])
{ // clear out our story item caches...
item = [[NSMutableDictionary alloc] init];
currentUserId = [[NSMutableString alloc] init];
currentError = [[NSMutableString alloc] init];
}
}
}
项目的变量分配:
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
//DLog(@"ended element: %@", elementName);
if([MethodName isEqualToString:@"SignInStep"])
{
if ([elementName isEqualToString:@"item"])
{ // save values to an item, then store that item into the array...
[item setObject:currentUserId forKey:@"userId"];
[item setObject:currentError forKey:@"error"];
[SignIn addObject:[item copy]]; //Method returns Objective C Object with +1 retain count
}
}
}//Object leaked: allocated object is not referenced later in this execution path and has a retain count of +1
我收到以下错误:
1) Method returns Objective C Object with +1 retain count
2) Object leaked: allocated object is not referenced later in this execution path and has a retain count of +1
我在上面的代码中提到了我到底是在哪里收到这些泄漏的。谁能告诉我这是什么原因造成的?
最佳答案
You must relinquish ownership of an object you own
id obj = [item copy];
[SignIn addObject:obj]; // SignIn will retain obj
[obj release];
看看Memory Management Programming Guide
item = [[NSMutableDictionary alloc] init]; // release this object
currentUserId = [[NSMutableString alloc] init]; // release this object
currentError = [[NSMutableString alloc] init]; // release this object
关于ios - 复制对象时客观内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13074725/