为什么我的阵列总是零?

时间:2015-04-18 22:11:07

标签: swift

我真的不知道发生了什么,我真的很困惑为什么会这样。我可能做错了但是当我尝试从函数中访问我的数组时,其中没有任何内容。如果有人可以帮助我,请告诉我。

import UIKit

class withFriendsView: UITableViewController {

    var withFriendsArray:NSMutableArray = NSMutableArray()
    var friendImg = [PFFile]()
    var friendusername = [String]()
    var friendName = [String]()

    override func viewDidLoad() {
        super.viewDidLoad() 
    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)

        loadWithFriends()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning() 
    }



    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {

        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return friendusername.count
    }


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

        let cell:WithFriendsCell = tableView.dequeueReusableCellWithIdentifier("withFriends", forIndexPath: indexPath) as! WithFriendsCell

        friendImg[indexPath.row].getDataInBackgroundWithBlock {
            (data:NSData?, error:NSError?) -> Void in

            let img = UIImage(data: data!)

            cell.friendsImage.image = img
        }

        return cell
    }

    func loadWithFriends() {

        var channelQuery = ChannelQuery.query()!
        var activityQuery = ActivityQuery.query()!

        channelQuery.whereKey("Host", matchesKey: "ActChannel", inQuery: activityQuery)
        channelQuery.whereKey("Host", equalTo: "kia495")
        var data = channelQuery.findObjects()

        if data!.count != 0 {

        for objects in data! {

                let username = objects["Users"]!!.objectId

                let predicate = NSPredicate(format: "objectId == %@", username!!)
                var userQuery = PFQuery(className: "_User", predicate: predicate)
                var objects = userQuery.findObjects()

                for object in objects! {

                    friendImg.append(object.objectForKey("profileImage") as! PFFile)
                }
            }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

这个findObjectsInBackgroundWithBlock看起来像一个异步方法,会立即返回。只有在数据就绪时才会执行块中的代码。因此,当您尝试从friendImg访问数据时,它可能尚未就绪,您将获得零。

如果数据不是很大,您可以使用同步方法来执行此操作。

答案 1 :(得分:0)

您应该在向数组添加元素后重新加载表

首先将loadWithFriends()viewDidAppear移至viewDidLoad

在这一行中,您将返回另一个数组,请尝试返回friendImg.count

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return friendusername.count
}
相关问题