Swift错误:致命错误:无法索引空缓冲区
问题描述:
我是Swift语言的新手。我创建了一个MapKit应用程序,它从Sqlite DB(最新FMDB堆栈)递归检索MKPointAnnotation
数据(经纬度,日志和标题)。Swift错误:致命错误:无法索引空缓冲区
目的是在MKMapViewDelegate
上放置一堆兴趣点。我已经尝试了w/out数组,但是mapView.addAnnotation
覆盖了任何点并仅显示了地图上的最后一个点,所以我尝试使用数组。
我已经创建了一个函数,但是当调用wpoint数组时,我在运行时遇到了错误“致命错误:无法索引空缓冲区”。
下面的代码:
func initializeRoute()
{
sharedInstance.database!.open()
var resultSet: FMResultSet! = sharedInstance.database!.executeQuery("SELECT * FROM Route", withArgumentsInArray: nil)
// DB Structure
var DBorder: String = "order" // Int and Primary Index
var DBlatitude: String = "latitude" // Float
var DBlongitude: String = "longitude" // Float
// Array declaration
var wpoint: [MKPointAnnotation] = []
// Loop counter init
var counter: Int = 0
if (resultSet != nil) {
while resultSet.next() {
counter = counter + 1
wpoint[counter].coordinate = CLLocationCoordinate2DMake(
(resultSet.stringForColumn(String(DBlatitude)) as NSString).doubleValue,
(resultSet.stringForColumn(String(DBlongitude)) as NSString).doubleValue
)
wpoint[counter].title = resultSet.stringForColumn(DBorder)
mapView.addAnnotation(wpoint[counter])
}
}
sharedInstance.database!.close()
}
println ("Coordinate = \(wpoint.coordinate)")
显示所有的数据,我搞乱数组声明中的一些信息
答
数组声明:
var wpoint: [MKPointAnnotation] = []
创建空数组(零元素)。
然后,随着Swift documentation说:
It is not possible to insert additional items into the array using subscripting:
这就是为什么你的 “致命错误:无法索引空缓冲区” 的错误后来在这条线:
wpoint[counter].coordinate = ...
相反,如文档中所述,请使用append
方法或+=
运算符。无论哪种方式,您需要在每次迭代中创建一个MKPointAnnotation
对象,设置其属性,将其添加到数组中,然后将它传递给addAnnotation
。例如:
var wpoint: [MKPointAnnotation] = []
if (resultSet != nil) {
while resultSet.next() {
let pa = MKPointAnnotation()
pa.coordinate = CLLocationCoordinate2DMake(
(resultSet.stringForColumn(String(DBlatitude)) as NSString).doubleValue,
(resultSet.stringForColumn(String(DBlongitude)) as NSString).doubleValue
)
pa.title = resultSet.stringForColumn(DBorder)
wpoint.append(pa)
//wpoint += [pa] //alternative way to add object to array
mapView.addAnnotation(pa)
}
}
请注意一些额外的东西:
- 的
wpoint
阵列是不是摆在首位真的有必要,因为你是在同一时间使用addAnnotation
(单数)和添加注释一个代码与wpoint
没有任何关系。 - 如果你真的想用
wpoint
和“一次全部”添加注释到地图中,然后在循环中,你应该注释仅添加到数组,然后后循环,调用addAnnotations
(复数)一次,并将其传递给整个阵列。 - 使用
counter
作为数组索引的原始代码假设第一个索引是1
(counter
已初始化为0
,但它在循环的顶部递增)。在Swift和许多其他语言中,数组索引是从零开始的。 - 一个小问题,但问题中的代码不是“递归”检索数据。它正在迭代地检索数据。例如,如果方法自己调用
initializeRoute
,则会递归。
谢谢Anna,我已经解决了重新声明Array:'var wpoint:Array = Array()',现在它可以工作! :) –
2015-01-10 16:49:31
我已经实施了你的建议,非常感谢! – 2015-01-10 17:03:22