objective-c - 将 Action 限制在每天一次

标签 objective-c ios nsdate ios5

在我的应用程序中,我希望允许用户每天只输入一次值。

如何确保存储的 NSDate 不在当天?我可以在忽略时间的情况下比较两个 NSDate 的日值吗?

最佳答案

日期只是 NSTimeIntervals 的包装器。他们没有本地时间的概念,所以你不能直接从他们那里得到一天的值(value)。

你可以像这样使用 NSDateFormatter:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy/MM/dd"];

NSString *today = [formatter stringFromDate:[NSDate date]];

NSString *dateToCompare = [formatter stringFromDate:someDate];

if ([dateToCompare isEqualToString:today])
{
    ...
}

日期格式化程序使用您本地的时区输出日期,因此您可以保证日期对于用户来说是正确的。

如果你真的想确保事件间隔超过 24 小时(以防止作弊),那就更容易了,只需这样做:

if ([date1 timeIntervalSinceDate:date2] > 3600*24)
{
    ...
}

更新:正如 abbood 在评论中指出的那样,创建 NSDateFormatter 对象可能会很昂贵/很慢,因此如果它们将被重用,您应该保留它们。

将它们存储在静态变量或单例中不是一个好主意,因为它们不是线程安全的,但您可以将它们存储在当前线程的 threadDictionary 中,如下所示:

//check for a cached formatter and recreate if needed
NSMutableDictionary *threadDict = [[NSThread currentThread] threadDictionary];
NSDateFormatter *formatter = threadDict[@"someUniqueKey"];
if (!formatter)
{
    //create the formatter
    formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy/MM/dd"];

    //cache the formatter
    threadDict[@"someUniqueKey"] = formatter;
}

//use the formatter
...

关于objective-c - 将 Action 限制在每天一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9134200/

相关文章:

ios - NSDateFormatter 是如何工作的?

iphone - iPhone OS 上的 NSDate dateByAddingTimeInterval 在哪里?

ios - Xcode:表达式不可分配

ios - 谷歌分析在 ios 崩溃前的最后一个屏幕

iphone - 使用延迟加载的 NSDictionary 信息的模型类

iphone - 更改 rootviewcontroller +[NSNotificationCenter dictationViewClass] 后出错

ios - 使位于按钮 1 下方的按钮 1 的底部边缘和按钮 2 的顶部边缘垂直居中对齐?

objective-c - 如何仅从核心数据中获取前 20 个对象

objective-c - 将 ISO 8601 转换为 NSDate

xcode - 确定给定年份中阵亡将士纪念日的 NSDate