上一次操作后操作无效

时间:2015-04-02 19:21:54

标签: ios swift parse-platform

我在社交网络应用程序方面取得了一些进展。我遇到了一个问题。我有一个ViewController,它提供了一个填充了我的解析数据库中的内容的TableView。在单元格中,我有一个RSVP按钮,它应该在点击时将基于indexPath的RSVP发送到数据库,并在再次单击时删除。我相信我的逻辑是正确的,然而,我一直收到错误:

  

上一次操作后操作无效。

我放置了一个断点来查找崩溃的原因,我发现它发生在rsvpButtonClicked IBOutlet函数中的addUniqueObject行。

有人能帮助我吗?我的代码如下。

import UIKit
import CoreLocation

class MainFeedViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet var eventsTable: UITableView!

var user = PFUser.currentUser()
var refresher: UIRefreshControl!

var eventId = [String]()
var eventNames = [String]()
var eventCity = [String]()
var imageFiles = [PFFile]()
var getEventsQuery = 0
var userRsvps = [NSArray]()
var rsvp = 0

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

override func viewWillAppear(animated: Bool) {
    refreshControl()
    //getMyRsvps()
}

override func viewDidAppear(animated: Bool) {
    let timer = NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: "eventQuery", userInfo: nil, repeats: false)
}


func getMyRsvps() {
    var getRsvps = PFUser.query()
    getRsvps.whereKey("objectId", equalTo: user.objectId)
    getRsvps.whereKeyExists("myrsvp")
    getRsvps.findObjectsInBackgroundWithBlock {
        (objects: [AnyObject]!, error: NSError!) -> Void in
        if error == nil {
            self.userRsvps.append(objects)
        }
    }
}


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

    let cell = self.eventsTable.dequeueReusableCellWithIdentifier("mainFeedContent") as MainFeedContentTableViewCell

    cell.eventName.text = eventNames[indexPath.row]
    imageFiles[indexPath.row].getDataInBackgroundWithBlock{
        (imageData: NSData!, error: NSError!) -> Void in
        if error == nil {
            let image = UIImage(data: imageData)
            cell.eventImage.image = image
        }
    }

    cell.rsvpButton.tag = indexPath.row
    cell.rsvpButton.addTarget(self, action: "rsvpButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)

    return cell
}

@IBAction func rsvpButtonClick(sender: UIButton) {
    var senderButton = sender
    println("Current row \(senderButton.tag)")

    var tempObject = eventId[senderButton.tag]
    println("\(tempObject)")

    PFUser.currentUser().addUniqueObject(tempObject, forKey: "myrsvp")
    PFUser.currentUser().saveInBackground()

}

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return eventId.count
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    let mainViewIdentifier = "showDetail"
    if segue.identifier == mainViewIdentifier {
        if let destination = segue.destinationViewController as? DetailViewController {
            if let feedIndex = eventsTable.indexPathForSelectedRow()?.row {
                destination.eventNames = eventNames[feedIndex]
                destination.eventId = eventId[feedIndex]
                destination.eventImagesFile = imageFiles[feedIndex]
            }
        }
    }
}

func eventQuery() {
    let getEventsQuery = PFQuery(className: "Events")
    getEventsQuery.whereKey("eventLocation", nearGeoPoint: user["location"] as PFGeoPoint, withinMiles: user["preferredDistanceEvents"] as Double)
    getEventsQuery.limit = 16
    getEventsQuery.findObjectsInBackgroundWithBlock {(objects: [AnyObject]!, error: NSError!) -> Void in
        if error == nil {
            println("Successfully retrieved \(objects.count) events")
            for object in objects {
                self.eventId.append(object.objectId)
                self.eventNames.append(object["eventName"] as String)
                self.eventCity.append(object["eventCity"] as String)
                self.imageFiles.append(object["eventPicture"] as PFFile)
                self.eventsTable.reloadData()
            }
        } else {
            println(error)
        }
    }
}

func refreshControl() {

    refresher = UIRefreshControl()
    refresher.attributedTitle = NSAttributedString(string: "Pull to refresh")
    refresher.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged)
    self.eventsTable.addSubview(refresher)

}

/*
func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {

    var height: CGFloat = scrollView.frame.size.height
    var contentYoffset: CGFloat = scrollView.contentOffset.y
    var distanceFromBottom: CGFloat = scrollView.contentSize.height - contentYoffset
    if distanceFromBottom <= height {
        println("End of Table")
        refresh()
    }
}
*/

func refresh() {
    self.getEventsQuery++
    if self.getEventsQuery < self.eventId.count {
        let refreshEventsQuery = PFQuery(className: "Events")
        refreshEventsQuery.whereKey("location", nearGeoPoint: user["location"] as PFGeoPoint, withinMiles: user["preferredDistanceEvents"] as Double)
        refreshEventsQuery.whereKey("objectId", notContainedIn: eventId)
        refreshEventsQuery.limit = 4
        refreshEventsQuery.findObjectsInBackgroundWithBlock {(objects: [AnyObject]!, error: NSError!) -> Void in
            if error == nil {
                println("Successfully retrieved \(objects.count) events")
                for object in objects {
                    self.eventNames.append(object["eventName"] as String)
                    self.eventCity.append(object["City"] as String)
                    self.imageFiles.append(object["eventPicture"] as PFFile)
                    self.eventId.append(object.objectId)
                    self.eventsTable.reloadData()
                }
            } else {
                println(error)
            }
        }
    } else {
        println("No More Events. Sorry")
    }
    self.refresher.endRefreshing()
}

func getuserlocation() {
    PFGeoPoint.geoPointForCurrentLocationInBackground { (geopoint: PFGeoPoint!, error: NSError!) -> Void in
        if error == nil {
            self.user["location"] = geopoint
            self.user.saveInBackground()
        }
    }
}

func getTodayDate(){
    var today = NSDate()
    var calendar = NSCalendar.currentCalendar()
    var flags = NSCalendarUnit.HourCalendarUnit | NSCalendarUnit.MinuteCalendarUnit
    var components = calendar.components(flags, fromDate: today)
    var hour = components.hour
    var minutes = components.minute

    println("Today is \(today). The time is \(hour):\(minutes)")
}

}

1 个答案:

答案 0 :(得分:0)

我认为这是解析中的一个错误(在与JS共享的代码中,因为我已经遇到了问题)。具体而言,当混合添加和删除PFObject方法来操作数组列时,会出现此失败。

我已经使用了以下两种解决方法并取得了一些成功:

  1. Delimit通过干预保存添加和删除。换句话说,构建您自己的addToColAndSaveremoveFromColAndSave便利方法。如果你已经打过其中一个,请不要打电话给对方,直到保存完成。
  2. 可能更容易:重构代码以避免在数组上添加/删除方法。相反,使用getter(JS中的get,iOS中的objectForKey:)来获取内存中的数组,然后本地操作它。使用sdk setter更新对象。