programing

CoreData : 경고 : 명명 된 클래스를로드 할 수 없습니다.

nasanasas 2020. 9. 4. 07:33
반응형

CoreData : 경고 : 명명 된 클래스를로드 할 수 없습니다.


Xcode 6.1을 사용하여 기존 Objective-C TV Show 앱을 새 Swift 버전으로 복제하고 있으며 CoreData에 몇 가지 문제가 있습니다.

4 개 엔티티의 모델을 만들고 NSManagedObject 하위 클래스 (Swift에서)를 만들었으며 모든 파일에는 적절한 앱 대상이 설정되었습니다 ( 'Compile Sources').

새 엔티티를 삽입하려고 할 때마다이 오류가 계속 발생합니다.

CoreData : 경고 : 엔티티 'Shows'에 대해 'Shows'라는 클래스를로드 할 수 없습니다. 클래스를 찾을 수 없습니다. 대신 기본 NSManagedObject를 사용합니다.

몇 가지 의견 :

Core Data에 저장할 때 부모-자식 컨텍스트 방식을 사용하여 백그라운드 스레딩을 허용합니다. 다음을 사용하여 ManagedObjectContext를 설정하여이를 수행합니다.

lazy var managedObjectContext: NSManagedObjectContext? = {
  // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
  let coordinator = self.persistentStoreCoordinator
  if coordinator == nil {
    return nil
  }
  var managedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.MainQueueConcurrencyType)
  managedObjectContext.persistentStoreCoordinator = coordinator
  return managedObjectContext
}()

다음을 사용하여 데이터를 저장합니다.

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
  var context = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.PrivateQueueConcurrencyType)
  context.parentContext = self.managedObjectContext!
  ...rest of core data saving code here...
})

이 경고는 Swift 구현의 세부 사항이 해결되는 동안 처리해야하는 단점 중 하나입니다. 경고는 허위로 발생합니다. 즉, 아래에 설명 된 단계를 따르지 않아도 설정이 작동 할 수 있습니다.

모델 편집기에서 클래스가 올바르게 설정되었는지 확인 하여 대부분의 경우 제거 할 수있었습니다 . 다른 많은 SOF 게시물 (이 질문에 대한 답변 포함)과 달리 모듈 이름 (예 :)을 포함하라는 제안이 도움 MyApp.Shows되지 않았습니다 .

다음 세 가지 항목을 확인하십시오.

1.
Xcode 7 베타 3까지 작동하는 버전

최대 XCode7 b3

귀하의 엔티티 이름을 더 적절한 단수로 수정했습니다.

Xcode 7.1의 Swift 2.0에서 작동하는 버전
(Xcode 7 베타 4 이상에서 작동해야 함)

모듈에서 "현재 제품 모듈"텍스트를 삭제해야합니다!

Xcode7 베타 3에서

2.
또한 빈번한 권장 사항을 따라야합니다.

@objc(Show)

수업 바로 위에.

참고 : Xcode 7 베타 4 이상을 사용하는 경우이 단계는 선택 사항입니다.

3.
또한 생성 된 관리 개체를 적절한 클래스 캐스팅 해야합니다 NSManagedObject. 기본값은 .

var newShow = NSEntityDescription.insertNewObjectForEntityForName("Show", 
                 inManagedObjectContext: context) as Show

SWIFT 2 / XCODE 7 업데이트 :

This issue (see my April 3 comment on this answer as well) is resolved in Swift 2 and XCode 7 beta release by Apple. So you actually now do not need @objc(myEntity) in Swift as answered by Mundi or using "MyAppName." before your Class name. It will stop working. So remove these, just put Class name in File and select Current Working Module as Module and cheers!

현재 작업 모듈 선택

But for those using @objc(myEntity) in Swift (like me), you can use this other solution instead which works smoothly.

In the xcdatamodel correct class in. It should look like this:

수업 설정

Here you go. Module.Class is the pattern for CoreData in Swift and XCode 6. You will also need the same procedure when using Custom Policy class in Model Policy or other CoreData stuff. A note: In image, The Name and Class should be Car and MyAppName.Car (or whatever the name of your entity). Here, User is a typo.


When using Xcode 7 and purely Swift, I actually had to remove @objc(MyClass) from my auto-generated NSManagedObject subclass (generated from Editor > Create NSManagedObject Subclass...).


In Xcode 7 beta 2 (and I believe 1), in the model configuration a new managed object of type File is set to the Module Current Product Module and the class of the object is shown in configuration as .File.

Xcode 7에서 "현재 제품 모듈"로 설정된 관리 개체 유형의 모듈

Deleting the module setting so it is blank, or removing the full stop so the class name in configuration is just File are equivalent actions, as each causes the other change. Saving this configuration will remove the error described.

Xcode 7에서 공백으로 설정된 관리 개체의 모듈


In Xcode 6.1.1 you do not need to add the @objc attribute since the base entity is a subset of an objc class (NSManagedObject) (see Swift Type Compatibility. In CoreData the full Module.Class name is required. Be aware the Module name is what is set in Build Settings -> Packaging -> Product Module Name. By default this is set to $(PRODUCT_NAME:c99extidentifier) which will be the Target's name.


With xCode 7 and Swift 2.0 version, you don't need to add @objc(NameOfClass), just change the entity settings in "Show the Data Model Inspector" tab like below -

Name - "Your Entity Name"

Class - "Your Entity Name"

Module - "Current Product Module"

여기에 이미지 설명 입력

Code for Entity class file will be like (in my code Entity is Family) -

import UIKit
import CoreData

class Family: NSManagedObject {

   @NSManaged var member : AnyObject
}

This example is working fine in my app with xCode 7.0 + swift 2.0


Do not forget to replace PRODUCT_MODULE_NAME with your product module name.

When a new entity is created, you need to go to the Data Model Inspector (last tab) and replace PRODUCT_MODULE_NAME with your module name, or it will result a class not found error when creating the persistent store coordinator.


You also need to use (at least with Xcode 6.3.2) Module.Class when performing your cast for example: Assuming your module (i.e. product name) is Food and your class is Fruit

let myEntity =  NSEntityDescription.entityForName("Fruit", inManagedObjectContext: managedContext)

let fruit = NSManagedObject(entity: myEntity!, insertIntoManagedObjectContext:managedContext) as! Food.Fruit

Recap:

  • Include module name when defining entity in Data Model Editor (Name: Fruit, Class: Food.Fruit)
  • When accessing the entity in code (i.e.SWIFT), cast it with Module.class (e.g. Food.Fruit)

Changing the Entity Class name in the Data Model editor to correspond to the class in question and adding @objc(NameOfClass) to file of each NSManagedObject right above the class declaration solved this problem for me during Unit Testing.


I also encountered a similar problem, follow these steps to resolve:

  1. The parent is NSManagedObject, not NSObject
  2. The module of an entity is default, not "Current Product Module"

나를 위해 일한 것은 (Xcode 7.4, Swift) <my actual class name>.<entity name>Entity inspector, 'Class'상자에서 클래스 이름을 변경하는 것 입니다.

관리 개체 하위 클래스의 내 개시자는 다음과 같습니다.

    convenience init(<properties to init>) {
    let entityDescr = NSEntityDescription.entityForName("<entity class name>", inManagedObjectContext: <managed context>)
    self.init(entity: entityDescr!, insertIntoManagedObjectContext: <managed context>)}
    //init properties here

참고 URL : https://stackoverflow.com/questions/26613971/coredata-warning-unable-to-load-class-named

반응형