iPhone:使用NSOperationQueue时内存泄漏

时间:2010-04-18 01:28:35

标签: iphone memory-leaks nsoperation

我坐在这里至少半小时才发现代码中有内存泄漏。 我刚刚使用NSOperationQueue将异步调用替换为(touch)方法的同步调用。 在我对代码进行更改后,Leak Inspector会报告内存泄漏。 使用NSOperationQueue的版本出了什么问题?

没有MemoryLeak的版本

-(NSData *)dataForKey:(NSString*)ressourceId_
{
   NSString *cacheKey = [self cacheKeyForRessource:ressourceId_]; // returns an autoreleased NSString*
   NSString *path = [self cachePathForKey:cacheKey]; // returns an autoreleased NSString*

   NSData *data = [[self memoryCache] objectForKey:cacheKey];
   if (!data)
   {
      data = [self loadData:path]; // returns an autoreleased NSData* 
      if (data)
      {
         [[self memoryCache] setObject:data forKey:cacheKey];
      }
   }
   [[self touch:path];
   return data;
}

带MemoryLeak的版本(我看不到任何内容)

-(NSData *)dataForKey:(NSString*)ressourceId_
{
   NSString *cacheKey = [self cacheKeyForRessource:ressourceId_]; // returns an autoreleased NSString*
   NSString *path = [self cachePathForKey:cacheKey]; // returns an autoreleased NSString*

   NSData *data = [[self memoryCache] objectForKey:cacheKey];
   if (!data)
   {
      data = [self loadData:path]; // returns an autoreleased NSData* 
      if (data)
      {
         [[self memoryCache] setObject:data forKey:cacheKey];
      }
   }
   NSInvocationOperation *touchOp = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(touch:) object:path];
   [[self operationQueue] addOperation:touchOp];
   [touchOp release];
   return data;
}

当然,触摸方法也没有什么特别之处。只需更改文件的日期。

-(void)touch:(id)path_
{
   NSString *path = (NSString *)path_;
   NSFileManager *fm = [NSFileManager defaultManager];
   if ([fm fileExistsAtPath:path])
   {
      NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:[NSDate date], NSFileModificationDate, nil];
      [fm setAttributes: attributes ofItemAtPath:path error:nil];
   }
}

0 个答案:

没有答案