问题描述
我通过一门课程的工作学习迅速。作为一个特定的项目方法的一部分,我创建一个名为全球字符串数组任务。
I am working through a course to learn swift. As part of a particular projects approach, I create a global string array called "tasks".
import UIKit
var tasks = [String]()
我遇到过的项目已要求,但现在我想要做的是使该阵列的应用程序的开口/倒闭之间永久的。迄今在使用过程中所描述的方法是使用
I have met the requirements for the project already, but now what I want to do is make that array permanent between app openings/closings. The method described in the course thus far is to use
override func viewDidLoad() {
NSUserDefaults.standardUserDefaults().setObject(tasks, forKey: "array")
}
这应该将数组保存。问题出现时,我回想一下数组。
This should save the array. The problem comes in when I try to recall the array.
我已经试过这两种方法里面viewDidLoad中():
I've tried both of these methods inside viewDidLoad():
tasks = NSUserDefaults.standardUserDefaults().objectForKey("array")! as! NSArray
和
let returnedArray = NSUserDefaults.standardUserDefaults().objectForKey("array")! as! NSArray
for i in returnedArray{
tasks.append(returnedArray[i])
}
第一次给出了错误的NSArray是不可转换为[字符串]';'!为你的意思使用给力垂头丧气?
The first gives the error "NSArray is not convertible to '[String]'; did you mean to use 'as!' to force downcast?"
第二个给出了错误无法转换类型的值元素(又名AnyObject')预期参数类型'诠释'。
The second gives the error "Cannot convert value of type 'Element' (aka 'AnyObject') to expected argument type 'Int'.
任何人都可以提供关于正在发生的事情一些指导?我仍然是一个相对的新手(仅在服用过程约2周)和大量的文件过于密集,我听不懂呢。
Can anyone provide some guidance on what is going on? I am still a relative newbie (only been taking the course for about 2 weeks) and a lot of the documentation is too dense for me to understand yet.
推荐答案
更改第一个
// tasks = NSUserDefaults.standardUserDefaults().objectForKey("array")! as! NSArray
tasks = defaults.objectForKey("array") as? [String] ?? [String]()
参考:的
这篇关于发行存储/中迅速恢复的全局字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!