2015-07-30 2 views
0

Привет, я новичок в swift и parse.com. Я пытаюсь заполнить свой массив уже сохраненными изображениями в синтаксическом анализе, попробуйте использовать dispatch_async, но не знаю, как это работает , heres код:заполнить массив изображений с помощью синтаксического анализа в swift

//imageArray declaration in table: 
var imageArray: Array<UIImage> = [] 


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CustomCell 

    var query = PFQuery(className: "ParseClass") 

    query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in 

     if(error == nil) { 

      let imageObjects = objects as! [PFObject] 

      for object in objects! { 

       let thumbNail = object["columnInParse"] as! PFFile 

       thumbNail.getDataInBackgroundWithBlock ({ (imageData: NSData?, error: NSError?) -> Void in 

        if (error == nil) { 

         if let image = UIImage(data:imageData!) { 

//here where the error appears: Cannot invoke 'dispatch_async' with an argument list of type '(dispatch_queue_t!,() -> _)' 
          dispatch_async(dispatch_get_main_queue()) {          
           cell.image.image = self.imageArray.append(image) 
          } 

         } 

        } 
       }) 
      } 
     } 
     else{ 

      println("Error in retrieving \(error)") 

     } 
    } 

    return cell 
} 

Надеюсь, вы, люди, понимаете этот код.

ответ

1

Правильный способ использовать этот блок отправки, как так:

dispatch_async(dispatch_get_main_queue(), {() -> Void in 
       //perform your work here 
       self.imageArray.append(image) 
       cell.image.image = imageArray[indexPath.row] 
      }) 

Другой причиной того, что компилятор дает это предупреждение, потому что вы пытаетесь добавить изображения в массив и набор, который, как образ клеток. То, что вы должны делать, показано выше.

Наконец, я бы рекомендовал переместить ваши запросы из cellForRowAtIndexPath: и в отдельные методы, так как это плохой дизайн кода.

Edit: Переписана способ привести примеры хорошего дизайна кода ...

var imageArray = [UIImage]() 

func performLookupQuery() { 
    var query = PFQuery(className: "ParseClass") 
    query.findObjectsInBackgroundWithBlock {(objects: [AnyObject]?, error: NSError?) 
     if error == nil { 
      let imageObjects = objects as! [PFObject] 
      for object in imageObjects { 
       let thumbnail = object["columnInParse"] as! PFFile 
       thumbnail.getDataInBackgroundWithBlock{(imageData: NSData?, error: NSError?) 
        if error == nil { 
         if let image = UIImage(data: imageData!) { 
          imageArray.append(image) 
          //now your imageArray has all the images in it that you're trying to display 
          //you may need to reload the TableView after this to get it to display the images 

         } 
        } 
       } 
      } 
     } 
     self.tableView.reloadData() 
    } 
} 

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) 
    cell.image.image = nil 
    cell.image.image = imageArray[indexPath.row] 
    return cell 
} 

Я не добавлял все проверки ошибок в методе запроса, как вы должны, я просто пишу это, чтобы показать, что вы бы сделали. Теперь, когда у вас есть этот метод запроса, вы можете вызвать его в viewDidLoad, а затем результаты будут доступны при попытке загрузить таблицу.

override func viewDidLoad(animated: Bool) { 
    super.viewDidLoad(animated) 
    self.performLookupQuery() 
} 
+0

И это даже не будет работать должным образом, потому что вы не можете вернуть ASync Клетка – milo526

+0

справа, следовательно, для перемещения рекомендованы кем его код запроса за пределами этого метода, вернуть его в массив 'UIImage', а затем используйте это, чтобы установить образ ячейки. – pbush25

+0

@ Daniel Я отредактировал свой ответ, чтобы дать вам обзор (неполный, поскольку он не реализует ваши другие методы и остальные методы 'tableView'' delegate', но, надеюсь, это поможет вам понять. – pbush25

Смежные вопросы