swift 3- [__nsarraym objectAtIndex:]:索引3超过界限[0.2]



我有一个14按钮,我对按钮有动作,在动画中,我的单词string构成了2个字符3,4,... 10字符,所以当我单击3按钮时,这是正确的问题

由于未见异常而终止应用程序'nsrangeException',原因:' - [__ __ nsarraym objectatiNdex:]:index 3超过界限[0 .. 2]'

如何解决此崩溃??

这是我的代码:

class QuestionView: UIViewController {
    var nsmutableArray1: NSMutableArray = []
    var nsmutableArray2: NSMutableArray = []
    var nsmutableArray3: NSMutableArray = []
    var nsmutableArray4: NSMutableArray = []
    var i : Int = 0
    func animateButton(sender: UIButton) {
        let xS = nsmutableArray1.object(at: i) as? Int ?? 0
        var yS = nsmutableArray2.object(at: i) as? Int ?? 0
        let widthS = nsmutableArray3.object(at: i) as? Int ?? 0
        let heightS = nsmutableArray4.object(at: i) as? Int ?? 0
        yS -= widthS
        let startS = CGPoint(x: xS, y: yS)
        let sizeS = CGSize(width: widthS, height: heightS)
        sender.frame = CGRect(x: startS.x, y: startS.y, width: sizeS.width, height: sizeS.width)
        UIView.animate(withDuration: 2, delay: 0, usingSpringWithDamping: 0.2, initialSpringVelocity: 6, options: .allowUserInteraction, animations: { [weak self] in
            sender.transform = .identity
            self?.i += 1
        }) { (finished) in
           }
    }

}

强烈建议您使用Swift Arrays:

var array1: [Int] = []

var array1: [CGFloat] = [] //you can use any type here

存储的var表示可以更改此数组(可变)

此崩溃意味着您要获得的对象的索引超出数组范围(您的数组不包含该索引上的任何对象)。

请记住,数组索引从0开始,这意味着要访问第一个对象,您应该使用:

array1[0]

相同的方式,如果您的数组包含四个对象,并且您想在索引3处获得一个对象,请设置以下方式:

 array1[3] //will access to the fourth object(the last one) in this array

因此,首先您需要检测您发送到数组的索引并检测数组数量有多少对象。使用:

array1.count

这将返回对象数组的计数。另外,您可以使用此参数避免崩溃:

if i < array1.count {
    //this index is in the array range use it to access to the object
    let xS = array1[i]
}else{
   //this index is out of the array range, using it will cause a crash
   //make a print of this array to detect why this array doesn't contain on object at this index (if it should contain)
    print(array1)
}

或仅将VAR设置为0,然后检查数组是否在数组中具有值不重要,是否如此重要,例如:

var xS = 0
 if i < array1.count {
        //this index is in the array range use it to access to the value
        xS = array1[i]
 }
//if array doesn't contain an object at that index, you won't have any changes for that var, at it will be equal 0

最新更新