当我尝试在NSMutableArray
内调用时,我需要知道为什么我的AllNews:Tableviewcell
为空。
类NewsTableViewController:UITableViewController {
var AllNews:NSMutableArray! = NSMutableArray()
var myEditImage = UIImage(named: "create_new-32.png")
func gotoCompose () {
self.performSegueWithIdentifier("gotoCompose", sender: self)
}
override func viewDidLoad() {
super.viewDidLoad()
//Getting the latest 5 news from the parse.com
var getNews = PFQuery(className: "News")
getNews.orderByDescending("CreatedAt")
getNews.limit = 5
getNews.findObjectsInBackgroundWithBlock {
(objects:[AnyObject]!, error:NSError!)->Void in
if error == nil{
for object in objects {
let news:PFObject = object as PFObject
self.AllNews.addObject(news)
//tableView.reloadData()
//println(object)
}
let array:NSArray = self.AllNews.reverseObjectEnumerator().allObjects
self.AllNews = NSMutableArray(array: array)
self.tableView.reloadData()
}
}
var homeButton: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Compose, target: self, action: Selector("gotoCompose"))
self.navigationItem.rightBarButtonItem = homeButton
}
override func viewDidAppear(animated: Bool) {
self.tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return 5
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
//
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("newsCell", forIndexPath: indexPath) as NewsTableViewCell
let herzNews:PFObject = self.AllNews.objectAtIndex(indexPath.row) as PFObject
var user = herzNews.objectForKey("newser") as? String
var content = herzNews.objectForKey("content") as? String
cell.userLabel.text = user!
cell.newsTextView.text = content!
return cell
}
}
我得到的错误是
[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array'
*** First throw call stack:
答案 0 :(得分:2)
问题:在viewDidLoad中,你开始下载,当下载完成后,你就把对象添加到AllNews(这是一个坏名字,不要以大写字母开头)。但是在下载完成之前,将调用cellForRowAtIndexPath。并且您将值5硬编码为行数,因此它需要一个包含5个字段的数组,但在调用它时,您的数组为空。如果你使用5的AllNews.count,它会很好。