1

我正在从用户的照片库中检索图像,并将该图像保存在文档目录中。我目前正在根据用户在文本字段中输入的内容命名图片。这可行,但文本字段并不是图片的好名称。我想使用某种唯一标识符来命名图片。

有什么想法或建议吗?我只是不想在用户保存大量照片时发生冲突。

4

3 回答 3

3

一种方法是使用 UUID。这是一个例子:

// return a new autoreleased UUID string
- (NSString *)generateUuidString
{
  // create a new UUID which you own
  CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);

  // create a new CFStringRef (toll-free bridged to NSString)
  // that you own
  NSString *uuidString = (NSString *)CFUUIDCreateString(kCFAllocatorDefault, uuid);

  // transfer ownership of the string
  // to the autorelease pool
  [uuidString autorelease];

  // release the UUID
  CFRelease(uuid);

  return uuidString;
}

或 ARC 版本:

// Create universally unique identifier (object)
CFUUIDRef uuidObject = CFUUIDCreate(kCFAllocatorDefault);

// Get the string representation of CFUUID object.
NSString *uuidStr = (__bridge_transfer NSString *)CFUUIDCreateString(kCFAllocatorDefault, uuidObject);
CFRelease(uuidObject);

更简单的 iOS6+ 解决方案:

NSString *UUID = [[NSUUID UUID] UUIDString];

更多信息在这里: http ://blog.ablepear.com/2010/09/creating-guid-or-uuid-in-objective-c.html 在这里: http : //en.wikipedia.org/wiki/Universally_unique_identifier

于 2012-08-27T23:42:49.493 回答
3

昨天我不得不用一些变化来解决同样的问题:将图片保存在临时目录中,因为图片将被上传到 Dropbox。

我所做的是获取自 UNIX 纪元以来重命名图像的秒数。

这是整个方法。您需要对其进行修改以满足您的需求,但您应该从中获得解决问题的要点:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *imageToUpload = [info objectForKey:UIImagePickerControllerOriginalImage];

    NSDate *dateForPictureName = [NSDate date];
    NSTimeInterval timeInterval = [dateForPictureName timeIntervalSince1970];
    NSMutableString *fileName = [NSMutableString stringWithFormat:@"%f", timeInterval];
    NSRange thePeriod = [fileName rangeOfString:@"."]; //Epoch returns with a period for some reason.
    [fileName deleteCharactersInRange:thePeriod];
    [fileName appendString:@".jpeg"];
    NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:fileName];
    NSData *imageData = [NSData dataWithData:UIImageJPEGRepresentation(imageToUpload, 1.0)];
    [imageData writeToFile:filePath atomically:YES];

    [[self restClient] uploadFile:fileName toPath:currentPath withParentRev:nil fromPath:filePath];

    [picker dismissModalViewControllerAnimated:YES];
}
于 2012-08-27T23:42:59.263 回答
0

假设您的目标是用户输入的内容具有您想要附加到照片的某些含义,那么只需在标题末尾增加一个数字,直到找到一个有效的数字

例如

野餐日.jpg

野餐日 1.jpg

野餐日 2.jpg

于 2012-08-27T23:43:57.447 回答