【问题标题】:How to put timestamp so that it won't duplicate when saving如何放置时间戳以使其在保存时不会重复
【发布时间】:2025-12-20 14:40:16
【问题描述】:

我想加一个时间戳,这样当我保存应用程序时可以避免重复 我正在使用代码

NSArray *directoryNames = [NSArray arrayWithObjects:@"hats",@"bottoms",@"right",@"left",nil];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder

    for (int i = 0; i < [directoryNames count] ; i++) {
        NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:[directoryNames objectAtIndex:i]];
        if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
            [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil]; //Create folder

        NSString *folderPath = [documentsDirectory stringByAppendingPathComponent:@"hats"]; // "right" is at index 2, per comments & code
        NSString *filePath = [folderPath stringByAppendingPathComponent:@"IMAGE_NAME_HERE.PNG"]; // you maybe want to incorporate a timestamp into the name to avoid duplicates
        NSData *imageData = UIImagePNGRepresentation(captureImage.image);
        [imageData writeToFile:filePath atomically:YES];
    }
} 

如何添加时间戳或其他内容?我只是想停止重复,所以它不需要是时间戳

【问题讨论】:

    标签: ios timestamp save


    【解决方案1】:

    您可以直接使用时间戳,并且没有重复的机会。检查下面的代码

    time_t unixTime = (time_t) [[NSDate date] timeIntervalSince1970];
    NSString *timestamp=[NSString stringWithFormat:@"%ld",unixTime];
    

    【讨论】:

    • 如果您不想要任何时间,只是希望它停止重复,例如计数或其他内容,会发生什么
    • 是的,您可以按计数器名称写入图像,例如 1,2,3,4... .png,并且可以通过从目录中获取文件列表并找到最大值来获取文件名..就像您在数据库中确定 MAX 一样
    • 你怎么能做到这一点?我想这样做
    【解决方案2】:

    您没有说清楚,但我怀疑您想要添加 日期 作为文件名的一部分。

    为此,您需要使用“NSDateFormatter”将 NSDate 对象(例如今天的日期?)转换为字符串。 Here is a related question that shows how to create that string.

    如果您不想将日期作为文件或文件夹名称的一部分,您也可以简单地检查文件是否已存在于文件夹路径中。如果确实存在,请不要写入 png 文件。

    【讨论】:

    • 我会分享更多我的代码如果你不想要日期并且只想停止重复会发生什么
    【解决方案3】:

    你可以使用这个NSDate选择器:

    - (NSTimeInterval)timeIntervalSince1970
    

    它返回自 1970 年 1 月 1 日 00:00:00 GMT 以来的秒数。

    例子:

    time_t getTime = (time_t) [[NSDate date] timeIntervalSince1970];
    

    您可以存储哪些内容,以便参考文件的保存时间。

    【讨论】:

    • 如果您不想要任何时间,只是希望它停止重复,例如计数或其他内容,会发生什么
    • 好吧,既然你有图像的名称,你可以随时检查它是否已经保存。基本上是一个 if 条件。
    • 是的,它被保存了,但它只是在服用时不断更换自己,我只想停止它。