MBProgressHUD 导致 iOS 应用程序崩溃 (Swift 2.0)

Posted

技术标签:

【中文标题】MBProgressHUD 导致 iOS 应用程序崩溃 (Swift 2.0)【英文标题】:MBProgressHUD causing iOS application to crash (Swift 2.0) 【发布时间】:2016-02-21 21:48:58 【问题描述】:

我有一个 ViewController 将用户输入保存到 CoreData 并在尝试保存后显示 MBProgressHUD 以说明保存是否成功。

我有一个 AddNewViewController 类

class AddNewViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate, UITextFieldDelegate 

@IBOutlet weak var inputErrorMessage: UILabel!
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var amountLabel: UILabel!
    @IBOutlet weak var dayPicker: UIPickerView!
    @IBOutlet weak var durationPicker: UIPickerView!
    @IBOutlet weak var nameTextField: UITextField!
    @IBOutlet weak var amountTextField: UITextField!
    @IBOutlet weak var notesTextField: UITextField!

//variable to contrain the origin view controller
var originVC: String?

    // variables to hold user input
    var name: String?
    var amount: Double?
    var notes: String?
    var durationDay: Double?
    var durationType: String?

// The days and duration options to display in the pickers
    var durationPickerDataSource = ["Day(s)","Week(s)","Month(s)","Year(s)"];
    var dayPickerDataSource = ["1","2","3","4","5","6","7","8","9","10","11","12"];

@IBAction func saveButton(sender: AnyObject) 
        CoreDataStatic.data.saveIncomeBudgetAndExpenses(originVC!, name: name!, amount: amount, durationDay: durationDay!, durationType: durationType!, notes: notes!)
    


/**
    The number of columns in the picker view.
    */
    func numberOfComponentsInPickerView(dayPickerView: UIPickerView) -> Int 
        return 1
    

    /**
    The number of items in the picker view. Equal to the number of days(12) and duration options(4) .
    */
    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int 
        if pickerView == durationPicker 
            return durationPickerDataSource.count;
        
        else 
            return dayPickerDataSource.count;
        
    

    /**
    Gets the titles to use for each element of the picker view.
    */
    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? 
        if pickerView == durationPicker
            durationType = durationPickerDataSource[row]
            return durationType
        
        else 
            durationDay = Double(dayPickerDataSource[row])
            return dayPickerDataSource[row]
        
    
/**
    Display acknowledgement if the Income, Budget or Fixed Expense saved.
    */
    func displayMessage(origin: String) 
        var message : String

        //Changes the message depending on what the user was trying to save.
        if CoreDataStatic.data.saved == true 
        message = "\(origin) saved!"
                    
        else if CoreDataStatic.data.saved == false 
            message = "Error: \(origin) failed to save!"
        
        else 
            message = "Error!"
        

        print(message)

        //displays acknowledgement for 2 seconds.
        /*let acknowledgement = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
        acknowledgement.mode = MBProgressHUDMode.Text
        acknowledgement.label.text = message
            acknowledgement.hideAnimated(true, afterDelay: 2)*/
    

override func viewDidLoad() 
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        self.durationPicker.dataSource = self;
        self.durationPicker.delegate = self;
        self.dayPicker.dataSource = self;
        self.dayPicker.delegate = self;
    

CoreData 类:

struct CoreDataStatic 
    static let data = CoreData()


public class CoreData 

    var appDel : AppDelegate

    //Manage a collection of managed objects.
    let context : NSManagedObjectContext

    //Describes an entity in Core Data.
    let incomeEntity : NSEntityDescription
    let budgetEntity : NSEntityDescription
    let fixedExpenseEntity : NSEntityDescription

    //Retrieve data from Core Data with the entity 'Scores'.
    let income = NSFetchRequest(entityName: "Income")
    let budget = NSFetchRequest(entityName: "Budget")
    let fixedExpense = NSFetchRequest(entityName: "FixedExpenses")

    //Set the key that needs updating which is always 'score'
    let nameKeyToUpdate = "name"
    let amountDayKeyToUpdate = "amountDay"
    let amountWeekKeyToUpdate = "amountWeek"
    let amountMonthKeyToUpdate = "amountMonth"
    let amountYearKeyToUpdate = "amountYear"
    let durationDayKeyToUpdate = "durationDay"
    let durationTypeKeyToUpdate = "durationType"
    let notesKeyToUpdate = "notes"

    var saved : Bool?

func saveIncomeBudgetAndExpenses(origin: String, name: String, amountDay: Double, amountWeek: Double, amountMonth: Double, amountYear: Double, durationDay: Double, durationType: String, notes: String) 

        //saving in enity depending on origin view controller
        let entity : NSEntityDescription
        if origin == "Income" 
            entity = NSEntityDescription.entityForName("Income", inManagedObjectContext: context)!
        
        else if origin == "Budget" 
            entity = NSEntityDescription.entityForName("Budget", inManagedObjectContext: context)!
        
        else 
            entity = NSEntityDescription.entityForName("FixedExpenses", inManagedObjectContext: context)!
        

        let saveNew = NSManagedObject(entity: entity,
            insertIntoManagedObjectContext:context)

        // add user input to the relevant entity
        saveNew.setValue(name, forKey: nameKeyToUpdate)
        saveNew.setValue(amountDay, forKey: amountDayKeyToUpdate)
        saveNew.setValue(amountWeek, forKey: amountWeekKeyToUpdate)
        saveNew.setValue(amountMonth, forKey: amountMonthKeyToUpdate)
        saveNew.setValue(amountYear, forKey: amountYearKeyToUpdate)
        saveNew.setValue(durationDay, forKey: durationDayKeyToUpdate)
        saveNew.setValue(durationType, forKey: durationTypeKeyToUpdate)
        saveNew.setValue(notes, forKey: notesKeyToUpdate)


    do 
    try context.save()
        print("saved")
        saved = true
    
    catch _ 
        print("didnt save")
        saved = false
        

        AddNewViewController().displayMessage(origin)
    

    init()
        appDel      = (UIApplication.sharedApplication().delegate as! AppDelegate)
        context     = appDel.managedObjectContext
        incomeEntity =  NSEntityDescription.entityForName("Income", inManagedObjectContext: context)!
        budgetEntity =  NSEntityDescription.entityForName("Budget", inManagedObjectContext: context)!
        fixedExpenseEntity =  NSEntityDescription.entityForName("FixedExpenses", inManagedObjectContext: context)!
    

此代码按预期运行,但是当 displayMessage() 函数中已注释掉的部分未注释时,我收到以下错误: “致命错误:在展开可选值时意外发现 nil”

由于行 self.durationPicker.dataSource = self;在覆盖 viewDidLoad()

任何帮助将不胜感激。

注意*,如果我在 saveButton 函数中调用 displayMessage(),那么代码会正常工作,因此不确定为什么在从 CoreData 类调用消息时它不起作用。

【问题讨论】:

【参考方案1】:

我不确定这是否是正确的方法,但我找到了解决方法。

创建了一个变量(bool),名为attemptSave,默认为false。

在 saveIncomeBudgetAndExpenses try and catch 中,attemptSave 更改为 true。

displayMessage() 函数现在在两个按钮点击中被调用,使用 if 语句检查尝试保存是否为是,如果是,则调用函数。

【讨论】:

以上是关于MBProgressHUD 导致 iOS 应用程序崩溃 (Swift 2.0)的主要内容,如果未能解决你的问题,请参考以下文章

ios toast提示框(MBProgressHUD)

IOS 第三方框架-MBProgressHUD

IOS - MBProgressHUD 设置自定义背景图片

iOS swift 给MBProgressHUD分类

iOS——MBProgressHUD详解

iOS MBProgressHUD 之带底板的加载提示