我创建了一个dataModel,我有一个任务.此任务有几个变量,但也有一个与事件的一对多链接.这些事件可能是添加图片或评论等内容,因此一项任务可能会有很多事件.我把它们联系起来,如下所示:
实体文件也设置为:
import CoreData class Task: NSManagedObject { @NSManaged var area : Area @NSManaged var pictures : [TaskPicture] @NSManaged var events : [Event] @NSManaged var requestedByDept : NSString? @NSManaged var requestedByUser : NSString? @NSManaged var workloadDept : NSString? @NSManaged var detailDescription : NSString? @NSManaged var status : NSString @NSManaged var uniqueId : NSString? @NSManaged var isActive : NSNumber @NSManaged var created : NSDate? @NSManaged var modified : NSDate? @NSManaged var thumbnail : NSData? }
和
import CoreData class Event: NSManagedObject { @NSManaged var task : Task @NSManaged var actionBy : NSString? @NSManaged var detailDescription : NSString? @NSManaged var status : NSString @NSManaged var uniqueId : NSString? @NSManaged var isActive : NSNumber @NSManaged var created : NSDate? @NSManaged var modified : NSDate? @NSManaged var type : NSString }
对我来说,这些看起来都很正确,但我可能错了.然后我在我的一个viewControllers中获取所有任务
var fetchedResultsController: NSFetchedResultsController { if _fetchedResultsController != nil { return _fetchedResultsController! } let fetchRequest = NSFetchRequest() let entity = NSEntityDescription.entityForName("Task",inManagedObjectContext: self.managedObjectContext) fetchRequest.entity = entity fetchRequest.fetchBatchSize = 20 let sortDescriptor = NSSortDescriptor(key: "created",ascending: false) fetchRequest.sortDescriptors = [sortDescriptor] let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest,managedObjectContext: self.managedObjectContext,sectionNameKeyPath: nil,cacheName: nil) aFetchedResultsController.delegate = self _fetchedResultsController = aFetchedResultsController var error: NSError? = nil if !_fetchedResultsController!.performFetch(&error) { println("Unresolved error \(error)") abort() } return _fetchedResultsController! }
我可以向您保证,managedObjectContext既是最新的,也是正确传递的.如果我尝试访问事件数组,则会出现问题.我使用获取每个任务
let foundTask : Task = self.fetchedResultsController.objectAtIndexPath(indexPath) as Task
使用cellForRowAtIndexPath,因为它在tableView中.这再次有效,但是当我尝试let event = foundTask.events [0]或类似的东西时,我的消息崩溃了
-[_NSFaultingMutableSet objectAtIndex:]: unrecognized selector sent to instance 0x17022e9c0
我已经尝试将数组转换为NSArray并使用像.firstObject这样的函数,并且还将它放入NSSet但它永远不会让我访问事件.看起来当提取任务时,事件不是,因此给出了数据错误.我希望它能在我需要它时获取事件,但同样,它不会这样做.对不起,很长的帖子,但我希望包含尽可能多的信息,因为我觉得你需要帮助我.请询问您是否需要更多信息,我会尽快回复.
非常感谢
解决方法
Core Data中的(无序)to-many关系表示为NSSet,而不是数组,
所以财产应该声明为
所以财产应该声明为
@NSManaged var events: NSSet
要将集转换为数组,请使用allObjects:
let events = foundTask.events.allObjects as [Event]
请注意,Xcode可以为您创建托管对象子类(编辑器 – >创建NSManagedObject Subclass …),我建议我避免这种错误.