将文件内容加载到NSArray

时间:2012-08-09 12:32:58

标签: iphone objective-c xcode ipad

我正在使用此代码将内容加载到NSArray并且它似乎工作正常但是检测泄漏的工具指出存在我无法指责的问题:

    - (void) loadPlan: (NSString  *) fName
    {

        short j1;

        fName= [NSString stringWithFormat:@"/%@",  fName];

        [self NewCase];

        NSArray *arrayPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *docDirectory = [arrayPaths objectAtIndex:0];

        NSString *filePath = [docDirectory stringByAppendingString:fName];
        BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath];

        if (!fileExists) return;

        NSString *fileContents = [NSString stringWithContentsOfFile:filePath
                                                           encoding:NSUTF8StringEncoding error:nil];


        NSArray *chunks = [fileContents componentsSeparatedByString: @"#"];


      for (i = 0; i <= 100; i++)
         {
            InputV[i] = [[chunks objectAtIndex: i+5] doubleValue];
         }


    ...    
      for (j1 = 0; j1 <= 10; j1++)
        {

            GroupMode[j1] = [[chunks objectAtIndex: 206+j1]   retain];   
        }


     ...
}

并在某个地方使用init方法:

for (j1 = 0; j1 <= 10; j1++)
     {
           GroupMode[j1] = [[NSString alloc] initWithFormat:@""];
     }

Instrument指向NSAraay * chunks行代码,但我不确定是什么问题。我是否需要在某个时候发布它?

我感谢任何帮助。

3 个答案:

答案 0 :(得分:2)

在评论中,您提到可以致电发布。因此,您没有使用ARC,因为我注意到您使用iphone标记了您没有使用GC。这留下了手动内存管理。

问题似乎是块数组或其中一些块都被重新保留(或未释放)。您没有显示所有代码,因此很难说。

确保您不会在未显示的代码中的其他位置保留其中任何一个。也许向我们展示loadPlan方法实现的其余部分。

编辑:现在你添加了更多代码,我也可以扩展这个答案。

回答这个问题:对释放的块的保留调用在哪里?

GroupMode的声明是什么?它似乎只是一个指针数组。如果是这样,您可能需要在设置新值之前释放旧值。

答案 1 :(得分:1)

让我根据您发布的内容尝试另一个答案。

我假设GroupMode是某个类的实例变量,并且声明如下:

NSString * GroupMode [11];

loadPlan中的第二个循环应为:

  for (j1 = 0; j1 <= 10; j1++)
    {
        NSString* aChunk = [chunks objectAtIndex: 206+j1];
        if ( GroupMode[j1] != aChunk ) {
            [GroupMode[j1] release];
            GroupMode[j1] = [aChunk retain];
        }   
    }

每次更改GroupMode的元素时都应该执行类似的操作,并且应确保在该类的dealloc方法中释放所有GroupMode持有的对象。

但是我建议你不要使用普通数组,而是转而使用NSArray和/或NSMutableArray。

答案 2 :(得分:0)

看一下这个答案:

"componentsSeparatedByString" Memory leak

问题可能是使用结果的东西过度保留了块中的东西。仪器指向此行,因为它是首次分配内存的地方,但它可能不是您问题的根源。