gpt4 book ai didi

iOS swift : Array index out of range when accessing last property

转载 作者:行者123 更新时间:2023-11-28 09:16:47 26 4
gpt4 key购买 nike

我遇到了一个奇怪的错误。我将一个项目附加到数组,然后通过 .last 属性访问该项目,但我随机收到“ fatal error :数组索引超出范围”。

这是我的代码(在 for 循环中):

var thisLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
currentMarkers.append(GMSMarker(position: thisLocation))

var calle = obj["calle"] as String
var numero = obj["numero"] as String
var colonia = obj["colonia"] as String
var direccion = "\(calle) \(numero), \(colonia)"
var horarioSemanal = obj["horario_lv"] as String
var horarioSabatino = obj["horario_s"] as String
var nombre = obj["sucursal"] as String

currentMarkers.last?.icon = UIImage(named: tipo.lowercaseString)
currentMarkers.last?.title = "\(tipo) - \(nombre)"
currentMarkers.last?.appearAnimation = kGMSMarkerAnimationPop
currentMarkers.last?.snippet = direccion

错误随机出现在最后四行之一。我还尝试通过以下方式访问它:

currentMarkers[currentMarkers.count-1].snippet = direccion

没有运气。

此代码是名为 fetchSucursales() 的函数的一部分,我在后台调用该函数,如下所示:

let qualityOfServiceClass = Int(QOS_CLASS_BACKGROUND.value)
let inverseQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
dispatch_async(inverseQueue, {

dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.labelStatus.text = "Obteniendo marcadores..."
self.activityIndicatorUpdateMarkers.startAnimating()
})

self.fetchSucursales()

dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.labelStatus.text = "\(self.currentMarkers.count) marcadores encontrados."
self.activityIndicatorUpdateMarkers.stopAnimating()
})

})

如果我在主队列中运行它,每次都一切正常:

    labelStatus.text = "Obteniendo marcadores..."
activityIndicatorUpdateMarkers.startAnimating()
fetchNearbyPlaces()
labelStatus.text = "\(currentMarkers.count) marcadores encontrados."
activityIndicatorUpdateMarkers.stopAnimating()

只是如果我这样做,我的应用程序会在获取标记时卡住。

它是随机的并且在不同的行(并且每次都经过不同数量的循环)这一事实让我认为它与它在后台运行有关。

我正在使用 Xcode 6.1 (6A1052d)。

希望你能帮助我,非常感谢!

编辑:

执行 Nate 的回答,现在错误已经转移到另一行,这里是我函数的开始:

func fetchSucursales() {

mapView.clear()
currentMarkers.removeAll(keepCapacity: false)
let fileManager = NSFileManager.defaultManager()
let enumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath(NSBundle.mainBundle().bundlePath)!
while let element = enumerator.nextObject() as? String {
if element.hasSuffix("json") {

let path = NSBundle.mainBundle().pathForResource(element.stringByDeletingPathExtension, ofType: element.pathExtension)
let jsonData = NSData(contentsOfFile: path!, options: .DataReadingMappedIfSafe , error: nil)
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(jsonData!, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
var sucursales : NSArray = jsonResult["markers"] as NSArray

sucursalLoop: for sucursal in sucursales {
let obj = sucursal as NSDictionary

var tipo = obj["tipo"] as String
var latitude:CLLocationDegrees = obj["latitud"]!.doubleValue
var longitude:CLLocationDegrees = obj["longitud"]!.doubleValue
if contains(searchedTypes, tipo.lowercaseString) {
//if latitude < mapRadius["norte"] && latitude > mapRadius["sur"] && longitude > mapRadius["este"] && longitude < mapRadius["oeste"] {

for var index:Int = 0; index < currentMarkers.count; ++index {
if latitude == currentMarkers[index].position.latitude && longitude == currentMarkers[index].position.longitude {
if tipo.lowercaseString == "cajero" {
continue sucursalLoop
}else {

if currentMarkers[index].title.rangeOfString("cajero") != nil {
currentMarkers.removeAtIndex(index)
}
//append
}
}
}

//Append
var thisLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
let newMarker = GMSMarker(position: thisLocation)
var calle = obj["calle"] as String
//Rest of code posted before

现在错误显示在 if latitude == currentMarkers[index].position.latitude && longitude == currentMarkers[index].position.longitude { 行或 if currentMarkers[index].title.rangeOfString("cajero ") != nil { 行。

我在 for 循环开始后添加了一个 println("(currentMakers.count)"),我看到它打印出一些垃圾。它会打印很多 1,然后是 2,然后是 3,直到 8,然后:

8
8
8
8
8
10
10
10
10
1100

1100

1100

1100

1100

1100

10
11
11
11
11

出错时,index为2,currentMakers.count为30。

最佳答案

您可以很容易地重构该代码,使其在数组中时不需要修改 GMSMarker 实例 - 这应该可以消除您看到的任何线程问题:

var thisLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
let marker = GMSMarker(position: thisLocation)

var calle = obj["calle"] as String
var numero = obj["numero"] as String
var colonia = obj["colonia"] as String
var direccion = "\(calle) \(numero), \(colonia)"
var horarioSemanal = obj["horario_lv"] as String
var horarioSabatino = obj["horario_s"] as String
var nombre = obj["sucursal"] as String

marker.icon = UIImage(named: tipo.lowercaseString)
marker.title = "\(tipo) - \(nombre)"
marker.appearAnimation = kGMSMarkerAnimationPop
marker.snippet = dirección
currentMarkers.append(marker)

关于iOS swift : Array index out of range when accessing last property,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27183049/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com