选择表格单元格时应用程序崩溃Swift

时间:2015-11-27 13:05:57

标签: ios swift uitableview swift2 segue

我已经尝试修复它,但是当我登录我的应用程序时,它会进入一个表视图控制器,当我点击一个单元格时,它会因为错误而终止,并且会因为NSException类型的未捕获异常而终止&# 39; ,它说信号中止,我不知道为什么。非常感谢任何帮助。

项目链接:https://www.dropbox.com/s/1d4d8opuxzpcuk4/TicketekApp.zip?dl=0

代码:

EventTableViewController(源视图控制器):

//  EventTableViewController.swift



import UIKit

class EventTableViewController: UITableViewController {
// MARK: Properties
var currentlySelectedIndex = 0
var events = [Event]()
var isAdmin: Bool = false
var currentUser: String = ""
override func viewDidLoad() {
    super.viewDidLoad()

    // Use the edit button item provided by the table view controller.
    if isAdmin == true {
    navigationItem.leftBarButtonItem = editButtonItem()
    }
    // Load any saved events, otherwise load sample data.
    if let savedEvents = loadEvents() {
        events += savedEvents
    } else {
        // Load the sample data.
        loadSampleEvents()
    }
}

func loadSampleEvents() {
    let photo1 = UIImage(named: "event1")!
    let event1 = Event(name: "ACDC", photo: photo1, rating: 4, price: 500.0, eventDescription: "Album", album: "Album1")!

    let photo2 = UIImage(named: "event2")!
    let event2 = Event(name: "Cold Play", photo: photo2, rating: 5, price: 500.0, eventDescription: "Album", album: "Album1")!

    let photo3 = UIImage(named: "event3")!
    let event3 = Event(name: "One Direction", photo: photo3, rating: 3, price: 500.0, eventDescription: "Album", album: "Album1")!

    events += [event1, event2, event3]
}

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

// MARK: - Table view data source

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

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

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    // Table view cells are reused and should be dequeued using a cell identifier.
    let cellIdentifier = "EventTableViewCell"
    let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! EventTableViewCell

    // Fetches the appropriate event for the data source layout.
    let event = events[indexPath.row]

    cell.nameLabel.text = event.name
    cell.photoImageView.image = event.photo
    cell.ratingControl.rating = event.rating
    cell.priceLabel.text = event.album

    return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    //Record the row selected
    currentlySelectedIndex = indexPath.row

    //check for your condition here something like
    if isAdmin {
        performSegueWithIdentifier("eventViewControllerSegue", sender: self)
    } else {
        performSegueWithIdentifier("userEventTableViewControllerSegue", sender: self)
    }
}

// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    // Return false if you do not want item to be editable.
    return true
}


// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == .Delete {
        // Delete the row from the data source
        events.removeAtIndex(indexPath.row)
        saveEvents()
        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
    } else if editingStyle == .Insert {
        // Create new instance of  class, add to the array, and add a new row to the table
    }
}


/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

}
*/

/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/


// MARK: - Navigation

// preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "eventViewControllerSegue"  {
        let eventDetailViewController = segue.destinationViewController as! EventViewController
        //Get the associated event
        eventDetailViewController.event = events[currentlySelectedIndex]
    } else  if segue.identifier == "userEventViewControllerSegue"  {
        let eventDetailViewController = segue.destinationViewController as! UserEventViewController
        //Get the associated event
        eventDetailViewController.event = events[currentlySelectedIndex]
        if let destinationVC = segue.destinationViewController as? UserEventViewController {

            destinationVC.currentUser = currentUser
        }
    }
    else if segue.identifier == "AddItem" {
        print("Adding new event.")
    }
}

@IBAction func unwindToMealList(sender: UIStoryboardSegue) {
    if let sourceViewController = sender.sourceViewController as? EventViewController, event = sourceViewController.event {
        if let selectedIndexPath = tableView.indexPathForSelectedRow {
            // Update an existing event.
            events[selectedIndexPath.row] = event
            tableView.reloadRowsAtIndexPaths([selectedIndexPath], withRowAnimation: .None)
        } else {
            // Add a new event.
            let newIndexPath = NSIndexPath(forRow: events.count, inSection: 0)
            events.append(event)
            tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Bottom)
        }
        // Save the events.
        saveEvents()
    }
}

// MARK: NSCoding

func saveEvents() {
    let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(events, toFile: Event.ArchiveURL.path!)
    if !isSuccessfulSave {
        print("Failed to save events...")
    }
}

func loadEvents() -> [Event]? {
    return NSKeyedUnarchiver.unarchiveObjectWithFile(Event.ArchiveURL.path!) as? [Event]
}
}

UserEventViewController(如果isAdmin为false,则为目标视图控制器):

//  EventViewController.swift



import UIKit

class UserEventViewController: UIViewController {
// MARK: Properties










@IBOutlet weak var eventDescriptionLabel: UITextView!

@IBOutlet weak var priceLabel: UILabel!

@IBOutlet weak var nameLabel: UILabel!

@IBOutlet weak var photoImageView: UIImageView!

@IBOutlet weak var albumNameLabel: UILabel!

@IBOutlet weak var myTitle: UINavigationItem!

@IBOutlet weak var ratingControl: RatingControl!

var event: Event?
var currentUser: String = ""

override func viewDidLoad() {
    super.viewDidLoad()



    // Set up views if editing an existing event.
    if let event = event {
        myTitle.title = event.name
        nameLabel.text   = event.name
        photoImageView.image = event.photo
        ratingControl.rating = event.rating
        eventDescriptionLabel.text = event.eventDescription
        albumNameLabel.text = event.album
        priceLabel.text = String(event.price)
    }
    }





override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "BuyTickets" {
        if let destinationVC = segue.destinationViewController as? seatsPickerViewController{
            destinationVC.price = event!.price
            destinationVC.name = event!.name
            destinationVC.album = event!.album
            destinationVC.photo = event!.photo
            destinationVC.currentUser = currentUser
        }
                }

}


}

EventViewController(如果isAdmin为true,则为目标视图控制器):

//  EventTableViewController.swift



import UIKit

class EventTableViewController: UITableViewController {
// MARK: Properties
var currentlySelectedIndex = 0
var events = [Event]()
var isAdmin: Bool = false
var currentUser: String = ""
override func viewDidLoad() {
    super.viewDidLoad()

    // Use the edit button item provided by the table view controller.
    if isAdmin == true {
    navigationItem.leftBarButtonItem = editButtonItem()
    }
    // Load any saved events, otherwise load sample data.
    if let savedEvents = loadEvents() {
        events += savedEvents
    } else {
        // Load the sample data.
        loadSampleEvents()
    }
}

func loadSampleEvents() {
    let photo1 = UIImage(named: "event1")!
    let event1 = Event(name: "ACDC", photo: photo1, rating: 4, price: 500.0, eventDescription: "Album", album: "Album1")!

    let photo2 = UIImage(named: "event2")!
    let event2 = Event(name: "Cold Play", photo: photo2, rating: 5, price: 500.0, eventDescription: "Album", album: "Album1")!

    let photo3 = UIImage(named: "event3")!
    let event3 = Event(name: "One Direction", photo: photo3, rating: 3, price: 500.0, eventDescription: "Album", album: "Album1")!

    events += [event1, event2, event3]
}

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

// MARK: - Table view data source

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

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

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    // Table view cells are reused and should be dequeued using a cell identifier.
    let cellIdentifier = "EventTableViewCell"
    let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! EventTableViewCell

    // Fetches the appropriate event for the data source layout.
    let event = events[indexPath.row]

    cell.nameLabel.text = event.name
    cell.photoImageView.image = event.photo
    cell.ratingControl.rating = event.rating
    cell.priceLabel.text = event.album

    return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    //Record the row selected
    currentlySelectedIndex = indexPath.row

    //check for your condition here something like
    if isAdmin {
        performSegueWithIdentifier("eventViewControllerSegue", sender: self)
    } else {
        performSegueWithIdentifier("userEventTableViewControllerSegue", sender: self)
    }
}

// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    // Return false if you do not want item to be editable.
    return true
}


// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == .Delete {
        // Delete the row from the data source
        events.removeAtIndex(indexPath.row)
        saveEvents()
        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
    } else if editingStyle == .Insert {
        // Create new instance of  class, add to the array, and add a new row to the table
    }
}


/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

}
*/

/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/


// MARK: - Navigation

// preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "eventViewControllerSegue"  {
        let eventDetailViewController = segue.destinationViewController as! EventViewController
        //Get the associated event
        eventDetailViewController.event = events[currentlySelectedIndex]
    } else  if segue.identifier == "userEventViewControllerSegue"  {
        let eventDetailViewController = segue.destinationViewController as! UserEventViewController
        //Get the associated event
        eventDetailViewController.event = events[currentlySelectedIndex]
        if let destinationVC = segue.destinationViewController as? UserEventViewController {

            destinationVC.currentUser = currentUser
        }
    }
    else if segue.identifier == "AddItem" {
        print("Adding new event.")
    }
}

@IBAction func unwindToMealList(sender: UIStoryboardSegue) {
    if let sourceViewController = sender.sourceViewController as? EventViewController, event = sourceViewController.event {
        if let selectedIndexPath = tableView.indexPathForSelectedRow {
            // Update an existing event.
            events[selectedIndexPath.row] = event
            tableView.reloadRowsAtIndexPaths([selectedIndexPath], withRowAnimation: .None)
        } else {
            // Add a new event.
            let newIndexPath = NSIndexPath(forRow: events.count, inSection: 0)
            events.append(event)
            tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Bottom)
        }
        // Save the events.
        saveEvents()
    }
}

// MARK: NSCoding

func saveEvents() {
    let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(events, toFile: Event.ArchiveURL.path!)
    if !isSuccessfulSave {
        print("Failed to save events...")
    }
}

func loadEvents() -> [Event]? {
    return NSKeyedUnarchiver.unarchiveObjectWithFile(Event.ArchiveURL.path!) as? [Event]
}
}

控制台输出:

2015-11-27 22:10:15.492 TicketekApp [14326:6837851] - 在仅变换图层中更改属性masksToBounds,将无效 2015-11-27 22:10:15.493 TicketekApp [14326:6837851] - 在仅变换图层中更改属性masksToBounds,将无效 2015-11-27 22:10:15.494 TicketekApp [14326:6837851] - 在仅变换图层中更改属性masksToBounds,将无效 2015-11-27 22:10:3​​7.900 TicketekApp [14326:6837851] *由于未捕获的异常终止应用程序' NSInvalidArgumentException',原因:' Receiver()没有带标识符的segue& #39; userEventTableViewControllerSegue'' * 第一次抛出调用堆栈: (     0 CoreFoundation 0x00251a94 exceptionPreprocess + 180     1 libobjc.A.dylib 0x0208fe02 objc_exception_throw + 50     2 UIKit 0x00e33960 - [UIViewController shouldPerformSegueWithIdentifier:sender:] + 0     3 TicketekApp 0x00023448 _TFC11TicketekApp24EventTableViewController9tableViewfS0_FTCSo11UITableView23didSelectRowAtIndexPathCSo11NSIndexPath_T_ + 424     4 TicketekApp 0x000234e9 _TToFC11TicketekApp24EventTableViewController9tableViewfS0_FTCSo11UITableView23didSelectRowAtIndexPathCSo11NSIndexPath_T_ + 89     5 UIKit 0x00dd5b79 - [UITableView _selectRowAtIndexPath:animated:scrollPosition:notifyDelegate:] + 1915     6 UIKit 0x00dd5dd0 - [UITableView _userSelectRowAtPendingSelectionIndexPath:] + 381     7 UIKit 0x00ddbff5 __38- [UITableView touchesEnded:withEvent:] _ block_invoke + 57     8 UIKit 0x00c7c37b _runAfterCACommitDeferredBlocks + 337     9 UIKit 0x00c90839 _cleanUpAfterCAFlushAndRunDeferredBlocks + 103     10 UIKit 0x00c9e4db _afterCACommitHandler + 102     11 CoreFoundation 0x0016b77e __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION + 30     12 CoreFoundation 0x0016b6de __CFRunLoopDoObservers + 398     13 CoreFoundation 0x0016105c __CFRunLoopRun + 1340     14 CoreFoundation 0x00160866 CFRunLoopRunSpecific + 470     15 CoreFoundation 0x0016067b CFRunLoopRunInMode + 123     16 GraphicsServices 0x044c7664 GSEventRunModal + 192     17 GraphicsServices 0x044c74a1 GSEventRun + 104     18 UIKit 0x00c6ecc1 UIApplicationMain + 160     19 TicketekApp 0x000266cc main + 140     20 libdyld.dylib 0x02b00a21 start + 1 ) libc ++ abi.dylib:以NSException类型的未捕获异常终止 (lldb)

3 个答案:

答案 0 :(得分:0)

您正在使用代码

 performSegueWithIdentifier("userEventTableViewControllerSegue", sender: self)

但是没有像这样的segue名字。您应该检查故事板以获得正确的名称。

答案 1 :(得分:0)

我认为这个问题就像你在控制台中说的那样#34;没有带标识符的segue' userEventTableViewControllerSegue'' "

转到故事板并将segue设置在应该的位置......它应该可以工作。 :)

答案 2 :(得分:0)

你需要改变下面的东西,因为你提到了错误的标识符,此类必须有父作为UINavigationController

performSegueWithIdentifier("userEventTableViewControllerSegue", sender: self)

performSegueWithIdentifier("userEventViewControllerSegue", sender: self)