我有一个NSFetchRequest,它返回多个名为" Duty"的NSManagedObjects。
如果成功则返回类似[Duty]的数组。
我想对数组进行枚举,并对每个职责做一些事情。这是在for循环中完成的。我的问题是循环中的任务返回为<<error type>>
,如下所示:
但是,如果我通过数组中的索引直接访问一个任务,那么结果很好,如下所示:
//Find duties for calendar export
var dutiesRequest = NSFetchRequest()
dutiesRequest.entity = NSEntityDescription.entityForName("Duty", inManagedObjectContext: managedObjectContext)
dutiesRequest.sortDescriptors = [NSSortDescriptor(key: "startDate", ascending: true)]
dutiesRequest.predicate = NSPredicate(format: "(startDate >= %@) AND (startDate <= %@)", fromDate, toDate)
var dutiesFetchError : NSError?
let duties = managedObjectContext.executeFetchRequest(dutiesRequest, error: &dutiesFetchError) as [Duty]
//If I get the duty by its index it works:
let duty = duties[0] as Duty
有人能发现原因吗?我的代码是错误的还是这可能是XCode中的错误?
感谢您的时间!
修改
对不起,我应该包含所有代码,因为当我删除一些早期的代码时问题就消失了。 我想确保操作不在主线程上执行,所以我调用了另一个线程,如下所示:
class func saveToCalendarInBackground(eventStore:EKEventStore, calendar:EKCalendar, fromDate: NSDate, toDate: NSDate, previousEventIDs: [String:String], managedObjectContext: NSManagedObjectContext, progress: (progress: Float!) -> (), completion:(newEventIDs: [String:String]!, error: NSError!) -> ()) -> Void {
//Run the operations on another thread (not main), but move the progress and completion closures to the main thread with GCD
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
//Find duties for calendar import
var dutiesRequest = NSFetchRequest()
dutiesRequest.entity = NSEntityDescription.entityForName("Duty", inManagedObjectContext: managedObjectContext)
dutiesRequest.sortDescriptors = [NSSortDescriptor(key: "startDate", ascending: true)]
dutiesRequest.predicate = NSPredicate(format: "(startDate >= %@) AND (startDate <= %@)", fromDate, toDate)
var dutiesFetchError : NSError?
let duties = managedObjectContext.executeFetchRequest(dutiesRequest, error: &dutiesFetchError) as [Duty]
//If I get the duty by its index it works:
//let duty = duties[0] as Duty
if dutiesFetchError == nil {
for duty in duties {
}
}
else {
//Return callbacks on main thread
dispatch_async(dispatch_get_main_queue(), {
completion(newEventIDs: nil, error: NSError(domain: "CalendarManagerDomain", code: 0, userInfo: [NSLocalizedFailureReasonErrorKey : "Found no duties for calendar export."]))
})
}
})
}
如果我删除
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { })
for循环正确地找到每个职责。
对此有何解释?