Ios 我不能让默认值按预期为我工作
我正在开发一个允许用户每天投票一次的应用程序。为了设置时间限制,我声明votingStatus布尔变量。它的值取决于controlDate,如果第一次运行应用程序,然后votingStatus为true,则controlDate可以为零 但是,应用程序不能正常工作。votingStatus变量仅在重置应用程序后更改其值。这显然不是我所期望的。每次用户单击按钮时,我都需要检查和更新votingStatus变量 提前感谢您分享如何更正应用程序流程的想法 下面是我在类ViewController中编写的代码:UIViewController{}Ios 我不能让默认值按预期为我工作,ios,iphone,swift,Ios,Iphone,Swift,我正在开发一个允许用户每天投票一次的应用程序。为了设置时间限制,我声明votingStatus布尔变量。它的值取决于controlDate,如果第一次运行应用程序,然后votingStatus为true,则controlDate可以为零 但是,应用程序不能正常工作。votingStatus变量仅在重置应用程序后更改其值。这显然不是我所期望的。每次用户单击按钮时,我都需要检查和更新votingStatus变量 提前感谢您分享如何更正应用程序流程的想法 下面是我在类ViewController中编写
var votingStatus: Bool?
@IBAction func yesButtonPressed(sender: AnyObject) {
//Check if votingStatus is true
if votingStatus == true {
//I'm using Parse for backend
var score = PFObject(className: "score")
score.setObject(1, forKey: "vote")
score.saveInBackgroundWithBlock{
(succes: Bool!, error: NSError!) -> Void in
if succes == true {
println("Done with ID \(score.objectId)")
//update NSUserdefaults
NSUserDefaults.standardUserDefaults().setObject(NSDate(), forKey: "controlDate")
// should I NSUserDefaults.standardUserDefaults().synchronize() below?
} else {
println(error)
//show alert
}
}
} else {
println("Status is \(votingStatus)")
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Find if user haven't already voted within 1 day so if his/her voting status true
// var votingStatus: Bool?
//To retrive the control date value. First time it has nil value
var controlDate = NSUserDefaults.standardUserDefaults().objectForKey("controlDate") as? NSDate
var timeInterval = controlDate?.timeIntervalSinceNow
var dayInSeconds = 24.0 * 3600
if controlDate == nil {
votingStatus = true
} else {
if timeInterval < dayInSeconds {
votingStatus = false
} else {
votingStatus = true
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
viewDidLoad只调用一次,直到您的视图从内存中删除,所以若系统将应用程序保留在内存中一周,则不会调用viewDidLoad。您可以在viewDidLoad之外设置一个日计时器,也可以像在yesButtonPressed func中的viewDidLoad一样检查controlDate值。我还没有测试过,只是简单回答一下:也许您的方法调用TimeIntervalsInnow的可选选项是问题所在。为什么不把这一行放到if块中,在那里你可以确定有一个值并用它包装起来!而不是
var dayInSeconds = 24.0 * 3600
if controlDate == nil {
votingStatus = true
} else {
**var timeInterval = controlDate!.timeIntervalSinceNow**
if timeInterval < dayInSeconds {
votingStatus = false
} else {
votingStatus = true
}
}
}
是的…如果这是您的问题,您应该调用synchronize。它将无法正常工作,但请思考对于过去的日期,ToIntervalenceNow将返回什么值?从现在起1分钟前是多少秒?换句话说,我现在需要加多少才能得到一分钟前的时间。然后看看你的比较。此外,viewDidLoad可能不是此代码的最佳位置-它将只执行一次。如果这一天到期,而这个视图仍然可见怎么办?你是否阅读了我对你之前问题的回答的评论?@Paulw11你是对的。非常感谢。我要修正时间间隔加负数。对吗?至于在哪里添加controlDate var检查代码,我目前还不知道。可能在func YesButton内按下。但是我不喜欢它。因为它不仅是视图的按钮,所有其他按钮也应该检查votingStatus。你能提出你的建议吗?这是个问题,但不是主要问题。主要问题是时间间隔将与过去一样为负,这使得