I can reproduce this bug, and there is nothing wrong with my code (tested thoroughly). If anyone else could reproduce this, I would greatly appreciate your corroboration. Afterwards, I will look for the appropriate place to submit this as a bug. I put this into 5 simple steps for anyone willing to test this bug. Your help is appreciated. Thanks 🙂 (Also, I tried turning off code optimization for the file to no avail.)
1) Create a Single View IOS app with Core Data support
2) Create a "Weekday" entity with 3 attributes (weekday : Int16, date: Date, isAllowed: Boolean)
3) From Editor menu, create NSManagedObject subclass with "use scalar properties for primitive data types" checked.
4) Add the 4 functions below to the AppDelegate.swift file
5) Add the following 2 lines of code to the ViewController.swift file
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let weekdays = appDelegate.getWeekdays()
//////////////////////////////////////////////////////////////////////
// 4 functions to add to AppDelegate.swift
func getWeekdays() -> [Weekday]
{
var weekdays = [Weekday]( count: 7, repeatedValue: Weekday() )
let fetchRequest = NSFetchRequest( entityName: "Weekday" )
do
{
var days = try managedObjectContext.executeFetchRequest( fetchRequest )
if( days.count == 0 )
{
createWeekdays()
days = try managedObjectContext.executeFetchRequest( fetchRequest )
}
for day in days
{
let weekday = day.weekday - 1
weekdays[weekday] = day as! Weekday
}
}
catch( let error as NSError )
{
print( error )
}
return weekdays
}
func createWeekdays()
{
let managedObjectContext = self.managedObjectContext
var date = self.getWeekStartDate()
let entityName = "Weekday"
for( var i = 1; i < 8; i++ )
{
let day = NSEntityDescription.insertNewObjectForEntityForName( entityName, inManagedObjectContext: managedObjectContext ) as! Weekday
day.weekday = Int16( i )
day.date = date.timeIntervalSince1970
day.isAllowed = false
date = getNextDay( date )
}
do
{
try managedObjectContext.save()
}
catch let error as NSError
{
print( "ERROR", error )
}
}
func getNextDay( today: NSDate ) -> NSDate
{
let calendar = NSCalendar.currentCalendar()
return calendar.dateByAddingUnit(.Day, value: 1, toDate: today, options: [] )!
}
func getWeekStartDate() -> NSDate
{
let currentDate = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components( .Weekday, fromDate: currentDate )
let weekday = components.weekday
let value = -1 * weekday
let weekStartDate = calendar.dateByAddingUnit( .Day, value: value, toDate: currentDate, options: [] )
return weekStartDate!
}