views:

118

answers:

1

Maybe this is a noob question, i have an NSURL from savePanel, and i want to save the file with such an identifier name. How to change the filename on NSURL?

here's my save method :

    for (int i=0; i<[rectCropArray count]; i++) {

   //the code goes on..

   CGImageDestinationRef dest = CGImageDestinationCreateWithURL(url, outputType, 1, nil);
   if (dest == nil) {
    NSLog(@"create CGImageDestinationRef failed");
    return NO;
   }

   CGImageDestinationAddImage(dest, imageSave, (CFDictionaryRef)dictOpts);

   //the code goes on..
  }

what i really want to do is, add the url filename every loop with i, so the method can save the different file on every loop. eg: SavedFile1.jpg, SavedFile2.jpg ...

thanks.

+2  A: 

NSURL has a initWithString:relativeToURL: method that you should be able to use for that. If you take the parent directory of the URL, the file name and the extension, you should be able to craft new URLs with relative ease.

NSURL* saveDialogURL = /* fill in the blank */;
NSURL* parentDirectory = [saveDialogURL URLByDeletingLastPathComponent];
NSString* fileNameWithExtension = saveDialogURL.lastPathComponent;
NSString* fileName = [fileNameWithExtension stringByDeletingPathExtension];
NSString* extension = fileNameWithExtension.pathExtension;

for (int i = 0; i < /* fill in the blank */; i++)
{
    NSString* newFileName = [NSString stringWithFormat:@"%@-%i.%@", fileName, i, extension];
    NSURL* newURL = [NSURL fileURLWithString:newFileName relativeToURL:parentDirectory];
    /* do stuff with newURL */
}
zneak
Thanks for the answer, but sorry i haven't add the most important info (my bad), i use the leopard 10.5 not the 10.6. The `URLByDeletingLastPathComponent` is a method for 10.6 as long as i know.
Hebbian
Update: Since i can't use the `URLByDeletingLastPathComponent`, i use the `NSString stringByDeletingLastPathComponent`, so it becomes the most expected one : `/Users/myName/Desktop/images/savedFile-6.png`. And then i allocate NSURL with `NSURL URLWithString:`, but the console shows an error : `<Error>: CGDataConsumer(url_close): write failed: -15.` Do i miss something?
Hebbian
@Hebbian Did your code work prior to this change? If you hardcode an URL, does it work? -15 means (as determined through `GetMacOSStatusErrorString(-15)`) `kCFURLImproperArgumentsError`, so it's likely you're giving it something unexpected.
zneak
problem solved : i change my `NSURL URLWithString:` with `NSURL fileURLWithPath:`, thanks for your answer @zneak. Now my `CGImageDestinationCreateWithURL method` has work smoothly. thanks many thanks.
Hebbian