我尝试在我自己的数组中运行它,但现在当我尝试从解析中获取它时,它给了我这个错误... 即使我在方括号中加上一个数字也不起作用。
@IBOutlet weak var questionLabel: UILabel!
@IBOutlet weak var answerTF: UITextField!
var question : String! = ""
var answer : String! = ""
var objectIDArray = [String]()
var randomID = 0
override func viewDidLoad() {
super.viewDidLoad()
let objectIdQuery : PFQuery = PFQuery(className: "QuestionsAndAnswers")
objectIdQuery.findObjectsInBackgroundWithBlock {
(objects : [PFObject]? , error : NSError?) -> Void in
var objectID = objects! as [PFObject]
for i in 0..<objectID.count {
self.objectIDArray.append(objectID[i].objectId!)
self.callData()
}
}
callData()
// Do any additional setup after loading the view.
}
func getRandomObjectID() {
randomID = Int(arc4random_uniform(UInt32(objectIDArray.count)))
}
func callData() {
getRandomObjectID()
let query : PFQuery = PFQuery(className: "QuestionsAndAnswers")
query.getObjectInBackgroundWithId(objectIDArray[randomID]) "<- The error is pointing here" {
(object : PFObject? , error : NSError?) -> Void in
if error == nil {
self.question = object!["Question"] as! String!
self.answer = object!["Answer"] as! String!
self.questionLabel.text = self.question
} else {
print(error)
}
}
}
答案 0 :(得分:0)
我认为问题发生在这里:
randomID = Int(arc4random_uniform(UInt32(objectIDArray.count)))
当random为3时,expample数组有3个数字。
你访问:objectIDArray(3)它超出范围,因为范围是[0..2]。
所以你把它改成:
randomID = Int(arc4random_uniform(UInt32(objectIDArray.count - 1)))
答案 1 :(得分:0)
我知道了,我使用了callData()两次,一次是在for循环中,另一次是在for循环之外。愚蠢的错误...
答案 2 :(得分:0)
我想可能的问题可能是这一行
var objectIDArray = [String]()
不允许以这种方式创建动态数组可能耗尽大量内存。请尝试使用此行
var objectIDArray = [String](count: 40, repeatedValue: "")