一千萬個為什麽

搜索

iPhone:使用NSOperationQueue時內存泄漏

我坐在這裏至少半小時在我的代碼中發現內存泄漏。 我只是使用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];
   }
}

最佳答案

暫時沒有最佳答案

轉載註明原文: iPhone:使用NSOperationQueue時內存泄漏