gpt4 book ai didi

ios - Swift 2.0 中多对多 NSManagedObject 关系查找导致崩溃

转载 作者:行者123 更新时间:2023-11-29 01:43:03 27 4
gpt4 key购买 nike

我正在尝试使用子类化的 Swift 2.0 NSManagedObject 在 Core Data 中实现多对多关系,但是每当我尝试获取关系中的对象时,我都会收到一个奇怪的无法识别的选择器发送到类 错误。

我尝试设计的关系如下所示:

enter image description here

关系的每一方都是无序的,因此应该在 Core Data 中表示为 NSSet。以下是我的类实现的样子:

TaggedContent.swift

import Foundation
import CoreData

class TaggedContent: NSManagedObject {
@NSManaged var tags: NSSet?
}

Tag.swift

import Foundation
import CoreData

class Tag: NSManagedObject {
@NSManaged var name: String?
@NSManaged var content: NSSet?
}

当我第一次启动我的应用程序时,我可以毫无问题地用数据填充我的数据存储。我遇到的问题是当我重新启动我的应用程序时。当我尝试通过 Tag.name 查找 TaggedContent 实例时,我继续遇到此崩溃的某些变体:

Crashed Thread:        0  Dispatch queue: NSManagedObjectContext 0x7fda82f934f0

Exception Type: EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000

Application Specific Information:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[CALayer __setObject:forKey:]: unrecognized selector sent to class 0x10426e4a8'
terminating with uncaught exception of type NSException
abort() called
CoreSimulator 179 - Device: iPhone 6 - Runtime: iOS 8.4 (12H141) - DeviceType: iPhone 6

Application Specific Backtrace 1:
0 CoreFoundation 0x0000000105e95c65 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x0000000106758bb7 objc_exception_throw + 45
2 CoreFoundation 0x0000000105e9cfad +[NSObject(NSObject) doesNotRecognizeSelector:] + 205
3 CoreFoundation 0x0000000105df313c ___forwarding___ + 988
4 CoreFoundation 0x0000000105df2cd8 _CF_forwarding_prep_0 + 120
5 CoreData 0x000000010ea7367c _PFCMT_SetValue + 988
6 CoreData 0x000000010ea71644 -[NSManagedObjectContext(_NSInternalAdditions) _retainedObjectWithID:optionalHandler:withInlineStorage:] + 196
7 CoreData 0x000000010eab4a9b _PFRetainedObjectIDCore + 331
8 CoreData 0x000000010eaa737e -[NSManagedObjectContext(_NestedContextSupport) _parentObjectsForFetchRequest:inContext:error:] + 862
9 CoreData 0x000000010eb1bc1d __82-[NSManagedObjectContext(_NestedContextSupport) executeRequest:withContext:error:]_block_invoke + 589
10 CoreData 0x000000010eaa6fd4 internalBlockToNSManagedObjectContextPerform + 84
11 libdispatch.dylib 0x0000000107024964 _dispatch_client_callout + 8
12 libdispatch.dylib 0x000000010700dfca _dispatch_barrier_sync_f_invoke + 76
13 CoreData 0x000000010eaa6eed _perform + 221
14 CoreData 0x000000010eaa6d18 -[NSManagedObjectContext(_NestedContextSupport) executeRequest:withContext:error:] + 296
15 CoreData 0x000000010ea602ca -[NSManagedObjectContext executeFetchRequest:error:] + 586

请注意,Core Data 正在尝试填充 CALayer 上的数据。我在这些崩溃日志中看到了几种不同的对象类型(例如 __NSCFString、__NSCFType、UICollectionViewLayoutAttributes 和 __NSArrayM 等),我很困惑为什么。我一直在想我一定错过了什么,但我找不到我错过的任何东西。如果有人知道为什么会发生这种情况,我很想知道,因为我目前陷入了这一点。

更新:我被要求提供导致崩溃的代码。我有一组用于简化获取请求的辅助方法,但是这个简单(并且有些人为的)示例也会导致相同的崩溃:

let fetchRequest = NSFetchRequest(entityName: "Tag")
fetchRequest.predicate = NSPredicate(format: "%K == %@", argumentArray: ["name", "pro"])

var results: [AnyObject] = []

do {
results = try managedObjectContext.executeFetchRequest(fetchRequest)
} catch let error {
NSLog("Error fetching data: \(error)")
}

if let tags = results as? [Tag] {
for tag in tags {
NSLog("Tag: \(tag.name)")

if let contentSet = tag.content {
for content in contentSet { // Crashes here when trying to access the first member of the set
NSLog(" * Content: \(content)")
}
}
}
}

最佳答案

看起来我的 Core Data 栈初始化顺序不对。我正在使用多上下文设置;我有一个连接到持久存储的私有(private)队列上下文和一个主队列上下文,用于将私有(private)上下文设置为其父级来完成我的所有常规工作。我还在后台线程中初始化我的持久存储,如 Core Data book 中所述.

我的初始化代码最初是这样的:

let optionalManagedObjectModel = NSManagedObjectModel(contentsOfURL: modelURL.NSURL)
assert(nil != optionalManagedObjectModel, "Failed to initialize managed object model for model URL \(modelURL.absoluteString)")

let managedObjectModel = optionalManagedObjectModel!
let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel)
let mainContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
let privateContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)

mainContext.parentContext = privateContext
privateContext.persistentStoreCoordinator = persistentStoreCoordinator

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
do {
try persistentStoreCoordinator.addPersistentStoreWithType(storeType, configuration: nil, URL: persistentStoreURL!.NSURL, options: nil)
} catch let error as NSError {
NSLog("Error initializing persistent store: \(error)")
} catch {
fatalError()
}

dispatch_async(dispatch_get_main_queue()) {
completion(mainContext) // handles finishing up app launch with data from the main context
}
}

如果我延迟设置 mainContext 的父上下文,直到配置持久存储之后,那么一切都按预期工作:

let optionalManagedObjectModel = NSManagedObjectModel(contentsOfURL: modelURL.NSURL)
assert(nil != optionalManagedObjectModel, "Failed to initialize managed object model for model URL \(modelURL.absoluteString)")

let managedObjectModel = optionalManagedObjectModel!
let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel)
let mainContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
let privateContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)

privateContext.persistentStoreCoordinator = persistentStoreCoordinator

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
do {
try persistentStoreCoordinator.addPersistentStoreWithType(storeType, configuration: nil, URL: persistentStoreURL!.NSURL, options: nil)
mainContext.parentContext = privateContext // do this after persistent store is set up
} catch let error as NSError {
NSLog("Error initializing persistent store: \(error)")
} catch {
fatalError()
}

dispatch_async(dispatch_get_main_queue()) {
completion(mainContext) // handles finishing up app launch with data from the main context
}
}

所以,事实证明我做错了什么,尽管过去(现在仍然)不清楚为什么这是必要的。我唯一能想到的是,在将父 NSManagedObjectContext 分配给子上下文时完成了一些任务,但我找不到它在任何地方的记录。我怀疑在后台初始化持久存储也可能是罪魁祸首。我以前在 Objective-C 中做过几次,没有遇到任何问题,所以很奇怪这会是 Swift 的问题。

关于ios - Swift 2.0 中多对多 NSManagedObject 关系查找导致崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32216188/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com