2015-01-14 2 views
0

일을 이해하기 쉽게하기 위해 사용자가 선택한 날짜를 입력하거나 생일 또는 특별 이벤트가 될 수있는 앱이 있습니다. 거기서 그 날짜를 핵심 데이터에 저장하고 내 TableViewController에서 결과를 가져옵니다. 보기가 나타날 때마다 모든 객체에서 날짜를 검색하고 차이를 얻기 위해 선택한 날짜에서 오늘 날짜를 빼기를 원합니다. tableView 다음 데이터를 다시로드합니다. 왼쪽 문제를 대체하고 데이터베이스에 저장할 때가되었습니다.핵심 데이터에서 속성의 새 값을 바꾸거나 설정하는 방법은 무엇입니까?

var myList: Array<AnyObject> = [] 

override func viewWillAppear(animated: Bool) { 

    let appDeleg: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate 
    let contexts: NSManagedObjectContext = appDeleg.managedObjectContext! 
    let freq = NSFetchRequest(entityName: "DaysLeft") 

    let sortDescriptor = NSSortDescriptor(key: "theDaysLeft", ascending: false) 
    freq.sortDescriptors = [sortDescriptor] 


    myList = contexts.executeFetchRequest(freq, error: nil)! 


    // Below automatically update the days left 

    for var index = 0; index < myList.count; index++ { 

     var data: NSManagedObject = myList[index] as NSManagedObject 

     var chosenDate: NSDate = data.valueForKey("chosenDate") as NSDate 
     var todayDate: NSDate = NSDate() 

     let calendar = NSCalendar.currentCalendar() 
     let components = calendar.components(.DayCalendarUnit, fromDate: todayDate, toDate: chosenDate, options: nil) 

     let secondsInADay = ((60 * 60) * 24) 
     let daysLeft: Int16 = (components.hashValue/secondsInADay) 

     //In my entity DaysLeft, I have the date the user chose stored as an attribute of type date as well as a theDaysLeft attribute of type Int16 
     myList[index].setValue(daysLeft, forKey: "theDaysLeft") 

    } 

    tableView.reloadData() 
+1

Errrr .... 많은 이유로, NSFetchedResultsController를 사용해야합니다. – quellish

+0

의견을 보내 주셔서 감사합니다. 나는 그것이 무엇인지 전혀 모르기 때문에 이에 대한 연구를 할 것입니다. 나는 프로그래밍에 익숙하지 않다. – user4363124

답변

2

것은 당신이 키 값 코딩을 사용하는 경우 : 내 문제는이 특정 라인에서, 나는

//In my entity DaysLeft, I have the date the user chose stored as an attribute of type date as well as a theDaysLeft attribute of type Int16 
     myList[index].setValue(daysLeft, forKey: "theDaysLeft") 

이 내 전체 코드는 "유형 INT16이 프로토콜 AnyObject을 준수하지 않습니다"라는 오류가 발생합니다 (KVC) 개체를 사용해야합니다. 유형이 Int16 인 변수 대신 NSNumber을 만들어야합니다. 예 : myList에서 검색된 값이 NSManagedObject 것을 제공 작동해야

myList[index].setValue(NSNumber(int16: daysLeft), forKey: "theDaysLeft") 

.

그래도 NSManagedObject 하위 클래스를 사용해야합니다. 편리하고 유효화 된 점 표기법을 사용하여 속성에 액세스 할 수 있으며 Int16과 같은 프리미티브를 사용할 수 있습니다.

+0

그레이트 솔루션! 고맙습니다. 코드를 약간 수정해야만했습니다. 이유는 xCode가 불평했습니다. 마지막 코드는 다음과 같습니다. myList [index] .setValue (NSNumber (short : daysLeft), forKey : "theDaysLeft") – user4363124

관련 문제