2
\$\begingroup\$

I have fetchData method which fills my imagesArray:

func fetchData(){

    let imageQuery = PFUser.query()
    imageQuery?.whereKey("username", containedIn: namesArray)

    imageQuery!.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in

        if error == nil {

            for object in objects! {
                print("\(object["username"] as! String)")

                self.imagesArray.append(object["image"] as! PFFile)
                if self.imagesArray.count == self.namesArray.count {
                    self.tableView.reloadData()
                    print("Names Order: \(self.namesArray)")
                }
            }
        } else {
            print("error: \(error?.localizedDescription)")
        }
    }
}

And I have tableView:cellForRowAtIndexPath method which uses this array to fill the UIImageView instance:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! ChatsCell
    cell.nameLabel.text = namesArray[indexPath.row]

    if imagesArray.count == namesArray.count && self.imagesLoaded == false{
        imagesArray[indexPath.row].getDataInBackgroundWithBlock { (imageData: NSData?, error: NSError?) -> Void in
            if error == nil {
                let image = UIImage(data: imageData!)
                cell.imageView?.image = image
                self.tableView.reloadData()
                self.imagesLoaded = true
            }
        }
    }

    return cell
}

Actually I use if condition for waiting my array imagesArray to be filled by query of another method and I use variable imagesLoaded to prevent infinite call of reloadData method. How can I write this method without if statement?

\$\endgroup\$
  • \$\begingroup\$ Welcome to Code Review! Why do you want to remove your if condition, do you think it's inelegant or inefficient? \$\endgroup\$ – SuperBiasedMan Jan 15 '16 at 10:55
  • \$\begingroup\$ @SuperBiasedMan yes I think so. I think It can be cleaner :) \$\endgroup\$ – wm.p1us Jan 15 '16 at 17:07
2
\$\begingroup\$

Is there any reason that imagesArray and namesArray have to be separated? If not, I probably will design a struct and join above two arrays to one since name and image can be fetched at the same time in func fetchData().

For example, let's assume we have a struct like:

struct Person {
    var username: String
    var image: PFFile
}

Then we have a global mutable array:

var items = [Person]()

Inside the for-loop in func fetchData(), we can create a new person and append it each time once we have a name and an image.

let person = Person(username: "myName", image: "myImage")
self.items.append(person)

Therefore, in the func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {}, we can get a person and associated username and image directly according to indexPath.row

let person = self.items[indexPath.row]
let username = person.username
let image = person.image

The benefits like this is that,

  • Cell count is restricted by self.items.count; therefore, no worries to take care of indexPath.row beyond an array.

  • Also username and image are always paired. It also helps to avoid concerning the order as imagesArray and namesArray are separated. No doubt, the condition imagesArray.count == namesArray.count can be removed as well.

  • As to boolean self.imagesLoaded which is able to be removed. Owing to before remote data has been fetched, self.items.count is 0 and none cell will be rendered at that moment.

\$\endgroup\$
  • \$\begingroup\$ It's a nice answer. But note that the appropriate style for code terms is using `` backticks `` and not **bold text** \$\endgroup\$ – janos Feb 7 '16 at 17:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.