0

假设我有一个指向我的 NSDocumentationDirectory 的 NSURL,但 NSURL 中有未知数量的子目录。写入 URL 时,我是否必须检查路径上的目录是否存在,如果它们不存在则创建它们,或者我可以只写入 NSURL 吗?如果是前者,我该怎么做?

这是我迄今为止尝试过的,但它不起作用。我认为这是因为路径上的子目录不存在。

NSData *imageData;
if (imageURL) {
   //imageURL points to an image on the internet.
   NSLog(@"Path components\n%@",[imageURL pathComponents]);
   NSFileManager *fileManager = [[NSFileManager alloc] init];
   NSArray *urls = [fileManager URLsForDirectory:NSDocumentationDirectory inDomains:NSUserDomainMask];
   //Sample of urls[0]: file://localhost/var/mobile/Applications/blahblah/Library/Documentation/
   NSURL *cachedURL = urls[0]; //iOS, so this will be the only entry.
   //Manually add a cache directory name.
   cachedURL = [cachedURL URLByAppendingPathComponent:@"cache"];
   NSArray *passedPathComponents = [imageURL pathComponents];
   for (NSString *pathComponent in passedPathComponents) {
      cachedURL = [cachedURL URLByAppendingPathComponent:pathComponent];
      NSLog(@"Added component %@ making URL:\n%@",pathComponent,cachedURL);
   }
   // Check if image data is cached.
   // If cached, load data from cache.
   imageData = [[NSData alloc] initWithContentsOfURL:cachedURL];
   if (imageData) {
      //Cached image data found
      NSLog(@"Found image data from URL %@",cachedURL);
   } else  {
      // Did not find the image in cache. Retrieve it and store it.
      // Else (not cached), load data from passed imageURL.
      //     Update cache with new data.
      imageData = [[NSData alloc] initWithContentsOfURL:imageURL];
      if (imageData) {
         // Write the imageData to cache
         [imageData writeToURL:cachedURL atomically:YES]; //This is the line I'm asking about
      }
   }
   NSLog(@"Value of urls is %@",urls[0]);
}

我对可以利用的缓存 API 不感兴趣。这个问题的目的是了解如何正确使用 NSFileManager。

编辑:我在想也许我需要在不包括最后一个组件的路径上使用 createDirectoryAtURL:withIntermediateDirectories:attributes:error: 。

4

1 回答 1

0

我使用 createDirectoryAtURL:... 让它工作,如下所示:

  for (NSString *pathComponent in passedPathComponents) {
     if ([pathComponent isEqualToString:lastComponent]) {
        //Now we're looking at the file name. Ensure the directory exists. What we have so far is the directory.
        if ([fileManager createDirectoryAtURL:cachedURL withIntermediateDirectories:YES attributes:nil error:NULL]) {
           //NSLog(@"Directory was created or already exists");
        } else {
           NSLog(@"Error creating directory %@",[cachedURL description]);
        };
     }
     cachedURL = [cachedURL URLByAppendingPathComponent:pathComponent];
  }
于 2013-03-28T20:06:48.083 回答