无法在Swift中索引空缓冲区

时间:2015-03-12 01:45:47

标签: ios xcode swift

我正在跟随Rob Percival关于Udemy的教程,我的应用程序崩溃时发生致命错误:无法索引空缓冲区。

错误发生在ViewdidLoad方法的以下行中:

userImage.image = UIImage(data: self.userImages[0])

在我错误的行上面使用println(self.userImages)我发现数组是空的。控制台输出[]。这一定是它崩溃的原因。正确的吗?

我的Parse.com信息中心显示我的所有用户都有图片。我不确定为什么数组会为空。有什么想法吗?

import UIKit

class SwipeViewController: UIViewController {


    var xFromCenter: CGFloat = 0

    var usernames = [String]()
    var userImages = [NSData]()
    var currentUser = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        println(PFUser.currentUser()["first_name"])

        PFGeoPoint.geoPointForCurrentLocationInBackground { (geopoint: PFGeoPoint!, error: NSError!) -> Void in

            println(error)

            if error == nil {

                println(geopoint)

                var user = PFUser.currentUser()

                user["location"] = geopoint


                var query = PFUser.query()
                query.whereKey("location", nearGeoPoint:geopoint)

                query.limit = 10
                query.findObjectsInBackgroundWithBlock({ (users, error) -> Void in

                    for user in users {

                        var gender1 = user["gender"] as? NSString
                        var gender2 = PFUser.currentUser()["interestedIn"] as? NSString

                        if gender1 == gender2 && PFUser.currentUser().username != user.username {

                            self.usernames.append(user.username)

                            // Update - chaned as to as!

                            self.userImages.append(user["image"] as NSData)

                        }


                    }

                    var userImage: UIImageView = UIImageView(frame: CGRectMake(0, 0, self.view.frame.width, self.view.frame.height))
                    println("images:")
                    println(userImage)
                    println(self.userImages)

                    userImage.image = UIImage(data: self.userImages[0])
                    userImage.contentMode = UIViewContentMode.ScaleAspectFit
                    self.view.addSubview(userImage)

                    var gesture = UIPanGestureRecognizer(target: self, action: Selector("wasDragged:"))
                    userImage.addGestureRecognizer(gesture)

                    userImage.userInteractionEnabled = true



                })

                user.save()

            }

        }






    }

    func wasDragged(gesture: UIPanGestureRecognizer) {



        let translation = gesture.translationInView(self.view)
        var label = gesture.view!

        xFromCenter += translation.x

        var scale = min(100 / abs(xFromCenter), 1)

        label.center = CGPoint(x: label.center.x + translation.x, y: label.center.y + translation.y)

        gesture.setTranslation(CGPointZero, inView: self.view)

        var rotation:CGAffineTransform = CGAffineTransformMakeRotation(xFromCenter / 200)

        var stretch:CGAffineTransform = CGAffineTransformScale(rotation, scale, scale)

        label.transform = stretch

        if label.center.x < 100 {

            println("Not Chosen")

        } else if label.center.x > self.view.bounds.width - 100 {

            println("Chosen")

        }

        if gesture.state == UIGestureRecognizerState.Ended {

            self.currentUser++

            label.removeFromSuperview()

            if self.currentUser < self.userImages.count {

                var userImage: UIImageView = UIImageView(frame: CGRectMake(0, 0, self.view.frame.width, self.view.frame.height))
                userImage.image = UIImage(data: self.userImages[self.currentUser])
                userImage.contentMode = UIViewContentMode.ScaleAspectFit
                self.view.addSubview(userImage)

                var gesture = UIPanGestureRecognizer(target: self, action: Selector("wasDragged:"))
                userImage.addGestureRecognizer(gesture)

                userImage.userInteractionEnabled = true

                xFromCenter = 0

            } else {

                println("No more users")

            }

        }
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
    }
    */

}

Error

1 个答案:

答案 0 :(得分:1)

看起来像数据问题。问题必须来自失败线上方的循环。

不满足条件,因此没有图像被推入阵列。原因可能是:

  • 您只有1位用户(您当前的用户)
  • 没有其他性别符合当前用户“感兴趣”状态的用户
  • 您的用户(当前与否)没有“性别”或“interestIn”属性设置

最好的方法是在你的循环中放置断点(或日志),以确定用户性别和“interestIn”属性,看看是否有匹配。