2016-09-24 9 views
0

私は毎月の経費を追跡するアプリを持っています。私は経費エンティティ現在の月の経費を追跡する属性が作成されています。私はここに示すように、毎月の費用をテーブルビューで表示します。ユーザーは左スイッチができ、費用はSwiftで空のオブジェクトを扱うにはどうすればいいですか?

@IBAction func backMonthButtonPressed(sender: AnyObject) { 
    print("Back Button Pressed") 
    currentMonth = NSCalendar.currentCalendar().dateByAddingUnit(.Month, value: -1, toDate: currentMonth, options: [])! 
    if checkMonth(currentMonth) { 
     updateFetch() 
     setMonth() 
    } else { 
     currentMonth = NSCalendar.currentCalendar().dateByAddingUnit(.Month, value: 1, toDate: currentMonth, options: [])! 
    } 
    tableView.reloadData() 

} 

@IBAction func nextMonthButtonPressed(sender: AnyObject) { 

    print("Next Button Pressed") 

    currentMonth = NSCalendar.currentCalendar().dateByAddingUnit(.Month, value: 1, toDate: currentMonth, options: [])! 
    if checkMonth(currentMonth) { 
     updateFetch() 
     setMonth() 
    } else { 
     currentMonth = NSCalendar.currentCalendar().dateByAddingUnit(.Month, value: -1, toDate: currentMonth, options: [])! 
    } 
    tableView.reloadData() 
} 

func checkMonth(month : NSDate) -> Bool { 
    let app = UIApplication.sharedApplication().delegate as! AppDelegate 
    let context = app.managedObjectContext //scratch pad 

    let fetchRequest = NSFetchRequest(entityName: "Expense") 
    fetchRequest.predicate = NSPredicate(format: "month == %@", month.MonthYearDateFormatter()) 
    let count = context.countForFetchRequest(fetchRequest, error: nil) 
    if count > 0 { 
     print("There are expenses for this month \(month.MonthYearDateFormatter()). Show expenses") 
     return true 

    } else { 
     print("There are no expenses for this month \(month.MonthYearDateFormatter()). Do Nothing") 
     return false 
    } 
} 

次または先月中にある右の場合にのみ、私の問題は、ユーザーが戻って6月に費用を作成し、作成しなかったとは考えにくいシナリオでは、これです8月の費用。どのように私は8月に彼/彼女の経費をそれをスキップせずに見たままにさせることができますか?何か案は?

+0

すべての費用を一度に取得し、月単位で並べ替えて配列に格納します。次に、配列をナビゲートします – Paulw11

答えて

1

私は精緻化する前に、いくつかの最適化をした:

@IBAction func backMonthButtonPressed(sender: AnyObject) { 
    self.processMonth(step: -1) 
} 

@IBAction func nextMonthButtonPressed(sender: AnyObject) { 
    self.processMonth(step: 1) 
} 

// a method uses almost the same code for both cases, so it was merged 
func processMonth(step: Int) { 
    let direction = (step < 1 ? "Back" : "Next") 
    print("\(direction) Button Pressed") 

    currentMonth = NSCalendar.currentCalendar().dateByAddingUnit(.Month, value: step, toDate: currentMonth, options: [])! 

    //if checkMonth(currentMonth) { 
    // I wouldn't test this because it locks you out from seeing empty month. 
     updateFetch() 
     setMonth() 
    //} 

    tableView.reloadData() 
} 

あなたが正確に求めてきたものへの答え:

あなたのUITableViewのためのデータソースが正しく設定されている場合は、あなたを介して行くことができるはず空ヶ月とにかく

// changed return type from `Bool` to `void` as I suggested in the method not to test empty month, as it could be useless 

func checkMonth(month : NSDate) { 
    let app = UIApplication.sharedApplication().delegate as! AppDelegate 
    let context = app.managedObjectContext //scratch pad 

    let fetchRequest = NSFetchRequest(entityName: "Expense") 
    fetchRequest.predicate = NSPredicate(format: "month == %@", month.MonthYearDateFormatter()) 
    let count = context.countForFetchRequest(fetchRequest, error: nil) 
    if count > 0 { 
     print("There are expenses for this month \(month.MonthYearDateFormatter()). Show expenses") 

    } else { 
     print("There are no expenses for this month \(month.MonthYearDateFormatter()). Do Nothing") 
     // here you can make some additional actions, like seeting the empty table with "no expenses this month" 
    } 
} 

しかし、Paulw11 @指摘として、データソースは、サイズ、排気ない場合には、たとえば、viewDidLoad/viewDidAppearでデータモデルからデータを取得し、次にcurrentMonth変数(ユーザーが現在表示されている月を参照)に従って各月をレンダリングすることができます。

この結果、setMonth()メソッドは、コントローラの負荷とユーザーが現在の月表示を変更するたびに呼び出されます。

0

@ Paulw11と@pedrouanの助けを借りて、私は欲しかったことをすることができました。

ユーザが過去の最初と最後の月

に行くからのviewDidLoad

の月
//If array is not empty, set first and last month 
    if expenses.count > 0 { 
     guard let first = expenses.first?.month else { 
      return 
     } 
     firstMonth = first 

     guard let last = expenses.last?.month else { 
      return 
     } 
     lastMonth = last 

    }else { 
     //Set current month to be first and last 
     firstMonth = currentMonth.MonthYearDateFormatter() 
     lastMonth = currentMonth.MonthYearDateFormatter() 
    } 

制限ユーザーをナビゲートすることができますどのくらいかを決定するために、最初と最後の月にすべての費用

func fetchExpenses() { 
    let app = UIApplication.sharedApplication().delegate as! AppDelegate 
    let context = app.managedObjectContext //scratch pad 
    let fetchRequest = NSFetchRequest(entityName: "Expense") 

    //Always Sort Budget by the date it's created 
    let sortDescriptor = NSSortDescriptor(key: "created", ascending: true) 
    fetchRequest.sortDescriptors = [sortDescriptor] 

    do { 
     let results = try context.executeFetchRequest(fetchRequest) 
     self.expenses = results as! [Expense] 
    } catch let err as NSError { 
     print(err.debugDescription) 
    } 
} 

セットの制約を取得

@IBAction func backMonthButtonPressed(sender: AnyObject) { 
    print("Back Button Pressed") 
    if currentMonth.MonthYearDateFormatter() != firstMonth { 
     self.processMonth(step: -1) 
    } 
} 

@IBAction func nextMonthButtonPressed(sender: AnyObject) { 

    print("Next Button Pressed") 
    if currentMonth.MonthYearDateFormatter() != lastMonth { 
     self.processMonth(step: 1) 
    } 
} 

現在の月のすべての費用を返し、n空のテーブルを1つクリアして返します。 pedroruanのprocessMonth()で

func updateFetch() { 
    setFetchResults() 

    do { 
     try self.fetchedResultsController.performFetch() 
    } catch { 
     let error = error as NSError 
     print("\(error), \(error.userInfo)") 
    } 
} 


func setFetchResults() { 

    let app = UIApplication.sharedApplication().delegate as! AppDelegate 
    let context = app.managedObjectContext //scratch pad 

    //Fetch Request 
    let fetchRequest = NSFetchRequest(entityName: "Expense") 

    let sortDescriptor = NSSortDescriptor(key: "created", ascending: false) 

    fetchRequest.predicate = NSPredicate(format: "month == %@", currentMonth.MonthYearDateFormatter()) 
    fetchRequest.sortDescriptors = [sortDescriptor] 
    let count = context.countForFetchRequest(fetchRequest, error: nil) 


    let controller = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: ad.managedObjectContext , sectionNameKeyPath: section, cacheName: nil) 

    //If there is none, empty fetch request 
    if count == 0 { 
     print("There are no expenses for this month. Show nothing") 
     controller.fetchRequest.predicate = NSPredicate(value: false) 
    } else { 
     print("There are expenses for this month. Show expenses") 
    } 

    fetchedResultsController = controller 
    controller.delegate = self 
} 

、私は、ユーザーがまだ6月の月へ行くことができることながら、8月が空であることを見ることができるように空tableViewsをナビゲートすることができました。みんなありがとう。

関連する問題