替换NSMutableArray的元素

时间:2015-02-28 20:33:45

标签: ios arrays swift nsuserdefaults

我在WeatherData数组中放了4个变量输入。我的数组似乎也将它们添加到适当的范围内(即[0] - [3]但实际上我想用新信息替换当前信息。

我最初的工作是:

if NSUserDefaults.standardUserDefaults().objectForKey("WeatherData")  != nil {

    WeatherData = NSUserDefaults.standardUserDefaults().objectForKey("WeatherData") as NSMutableArray

    DisplayInfo(WeatherData[0] as String, Temperature: WeatherData[1] as Int, Code: WeatherData[2] as String, Condition: WeatherData[3] as String)
}
然后我做了一些事情,最后我保存了它:

WeatherData.replaceObjectsInRange(0.3, withObjectsFromArray: [placemark.locality, Temperature, Code, Condition])

NSUserDefaults.standardUserDefaults().setObject(WeatherData as NSArray, forKey: "WeatherData")

随着每次迭代,我的数组变得更大,如下所示:

(
"San Francisco",
50,
33,
Fair,
"San Francisco",
50,
33,
Fair,
"San Francisco",
50,
33,
Fair,
"San Francisco",
50,
33,
Fair
)

但它应该只是

(
"San Francisco",
50,
33,
Fair,
)

意味着内容应该被替换并保存在NSUserDefaults中。

提前感谢您的帮助 王牌

2 个答案:

答案 0 :(得分:0)

问题是你的错误和我在Swift中的错误(我猜)的组合。

你这样说:

WeatherData.replaceObjectsInRange(0.3, withObjectsFromArray: [placemark.locality, Temperature, Code, Condition])

您正在传递0.3Double字面值),但replaceObjectsInRange:withObjectsFromArray:期望NSRange获得该参数。编译器应该在这里给你一个错误。

但相反,编译器会隐式将您的文字转换为NSMakeRange(0,0),因此replaceObjectsInRange:withObjectsFromArray:会在数组的开头插入新元素。

请改为尝试:

WeatherData.replaceObjectsInRange(NSRange(0 ... 3), withObjectsFromArray: [placemark.locality, Temperature, Code, Condition])

答案 1 :(得分:0)

感谢rob mayoff的帮助,以下是我的代码的副本:

if WeatherData.count == 0 {

    WeatherData.addObjectsFromArray([placemark.locality, Temperature, Code, Condition])

} else {

WeatherData.replaceObjectsInRange(NSRange(0 ... 3), withObjectsFromArray: [placemark.locality, Temperature, Code, Condition])

}