我对Swift很好,但对Objective-C很新。当用户点击警报视图上的按钮时,该按钮需要在接下来的24小时内被禁用。下面显示的代码是一个帮助方法,它将key:userId, value:timestamp
存储在NSUserDefaults
中 - 这是我从未真正使用过的。我有些担忧。
我的帮助方法在一个只有类方法的类中,所以即使我希望我的帮助方法是私有的,它也不能因为它调用了内部类方法。对于如何将其与其他物体隐藏起来感到困惑。
更好的逻辑程序?嵌套的if语句看起来很难看,如果它在我脑海中并不新鲜,可能很难阅读。
最好只复制alertAction
输入或使用inout,因为我只是启用或禁用基于逻辑的按钮。
方法的更好名称?其目的是启用/禁用基于逻辑的警报控制器,并存储在NSUserDefaults中。 configXXX似乎非常通用。
提前致谢。
+ (UIAlertAction *)configureAlertAction:(UIAlertAction *)alertAction
forUser:(id<BaseUser>)user {
/// Check User defaults to see if current user has reported this user already.
/// if not: store userID and timestamp 24 hours out in defaults and enable alert action.
/// If so, disable action.
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
UIAlertAction *modifiedAlertAction = alertAction;
double currentDate = [[NSDate date] timeIntervalSince1970];
double previousDate = [standardDefaults doubleForKey:user.userId];
if (previousDate) {
if (previousDate > currentDate) {
// remove from userdefaults..
[standardDefaults removeObjectForKey:user.userId];
// enable alert
[modifiedAlertAction setEnabled:YES];
} else if (previousDate > currentDate) {
[modifiedAlertAction setEnabled:NO];
}
} else {
// store in NSuserdefaults
[modifiedAlertAction setEnabled:YES];
double expirationDate = currentDate + 86400;
[standardDefaults setDouble:expirationDate forKey:user.userId];
}
return modifiedAlertAction;
}
答案 0 :(得分:0)
提出问题
如果你不喜欢嵌套的if语句,那就是我的建议
+ (UIAlertAction *)configureAlertAction:(UIAlertAction *)alertAction
forUser:(id<BaseUser>)user {
/// Check User defaults to see if current user has reported this user already.
/// if not: store userID and timestamp 24 hours out in defaults and enable alert action.
/// If so, disable action.
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
double currentDate = [[NSDate date] timeIntervalSince1970];
double previousDate = [standardDefaults doubleForKey:user.userId];
if (!previousDate) {
// store in NSuserdefaults
[alertAction setEnabled:YES];
double expirationDate = currentDate + 86400;
[standardDefaults setDouble:expirationDate forKey:user.userId];
return alertAction;
}
BOOL shouldEnableAlert = previousDate > currentDate;
if (shouldEnableAlert) {
// remove from userdefaults..
[standardDefaults removeObjectForKey:user.userId];
}
[alertAction setEnabled:shouldEnableAlert];
return alertAction;
}