ios - 复制对象时客观内存泄漏

标签 ios objective-c memory-leaks

我有一个示例应用程序,看起来像社交网络 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/

相关文章:

ios - xcassets 和自定义 URL 方案启动图像

html - iOS设备上的字体粗细问题

ios - 为什么我的 tableview 为每个单元格返回相同的 Parse 图像?

html - 如何添加请求网页的 UITextfield

Java Try-with-resource 在 Map 中存储输入流

python - Appium中如何获取iOS设备显示的最大宽高坐标?

iphone - 如何在编辑时更改 returnKeyType?

iphone - 发送到实例的无法识别的选择器

java - 在循环中创建位图时发生内存泄漏

.net - .NET 应用程序中与 native 堆相关的内存泄漏