[英]Swift3: How to use user default data in NSArray?
I have created a user default property called "data", which holds values of String
, meaning it is an array of String. 我创建了一个名为“ data”的用户默认属性,该属性包含
String
值,这意味着它是String的数组。 And I want to use Strings in the "data" as searchString
written below ("one", "two", "three")
. 我想将“数据”中的字符串用作
searchString
编写的searchString
("one", "two", "three")
。 I have created a method; 我创建了一个方法;
func getInput() -> [String] {
if let myData = userDefaults.array(forKey: "data") as? [String] {
return myData
}
return []
}
And I put the code inside NSArray.init()
, which looked like inside NSArray.init(getInput)
. 然后将代码放在
NSArray.init()
,看起来就像在NSArray.init(getInput)
。 However, an error came out, saying something like it is not NSArray, so I think it is the problem. 但是,出现错误,说不是NSArray,所以我认为这是问题所在。
func textViewDidChange(_ textView: UITextView) {
let attrStr = NSMutableAttributedString(string: mytextView.text)
let inputLength = attrStr.string.characters.count
let searchString : NSArray = NSArray.init("one", "two", "three")
for i in 0...searchString.count-1 {
let string : String = searchString.object(at: i) as! String
let searchLength = string.characters.count
var range = NSRange(location: 0, length: attrStr.length)
while (range.location != NSNotFound) {
range = (attrStr.string as NSString).range(of: string, options: [], range: range)
if (range.location != NSNotFound) {
range = NSRange(location: range.location + range.length, length: inputLength - (range.location + range.length))
mytextView.attributedText = attrStr
}
}
}
Also if there is a better way to save data from users rather than user defaults, could you tell me why and sample too. 另外,如果有一种更好的方法来保存用户数据而不是用户默认值,您能否告诉我原因并进行抽样。 But my main issue is how to access user default saved data and put the data into the
NSArray.init("*here*")
但是我的主要问题是如何访问用户默认保存的数据并将数据放入
NSArray.init("*here*")
In Swift it is batter if you use Swift native Array
and Dictionary
instead of NSArray
and NSDictionary
, but to answer your question you can initialize NSArray
with Swift type Array using initializer NSArray(array:)
. 在斯威夫特是连击,如果你使用SWIFT本地
Array
和Dictionary
,而不是NSArray
和NSDictionary
,但要回答你的问题,你可以初始化NSArray
使用初始化雨燕阵列NSArray(array:)
。
let searchString : NSArray = NSArray.init(array: getInput())
Or 要么
let searchString : NSArray = NSArray(array: getInput())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.