programing tip

NSManagedObject의 특정 하위 클래스를 찾을 수 없습니다

itbloger 2020. 6. 29. 08:13
반응형

NSManagedObject의 특정 하위 클래스를 찾을 수 없습니다


Core Data로 앱을 개발 중입니다. 다음을 사용하여 인스턴스를 만들 때 :

let entity = NSEntityDescription.entityForName("User", inManagedObjectContext: appDelegate.managedObjectContext)
let user = User(entity: entity, insertIntoManagedObjectContext: appDelegate.managedObjectContext)

로그에 경고가 있습니다.

CoreData: warning: Unable to load class named 'User' for entity 'User'.  Class not found, using default NSManagedObject instead.

어떻게 고칠 수 있습니까?

또 다른 질문은 NSManagedObject 서브 클래스에서 인스턴스 메소드를 어떻게 정의 할 수 있습니까?

편집하다:

다음 스크린 샷과 같이 엔티티 클래스를 지정했습니다.

여기에 이미지 설명을 입력하십시오


Xcode 7 업데이트 (최종) : Xcode 6 및 Xcode 7의 초기 베타 릴리스에서와 같이 모듈 이름을 클래스 앞에 추가 할 필요가 없습니다. 핵심 데이터 관리 객체 서브 클래스 구현 Apple 문서 가 이에 따라 업데이트되었습니다.

데이터 모델 인스펙터는 이제 엔티티에 대해 "Class"및 "Module"이라는 두 개의 필드를 갖습니다.

여기에 이미지 설명을 입력하십시오

엔티티에 대한 Swift 관리 오브젝트 서브 클래스를 작성할 때 "모듈"필드는 "현재 제품 모듈"로 설정되며이 설정으로 인스턴스 작성은 기본 응용 프로그램 및 단위 테스트 모두에서 작동합니다. 관리 객체 서브 클래스에 마크를 표시 해서는 안됩니다@objc(classname) ( https://stackoverflow.com/a/31288029/1187415 에서 관찰 됨 ).

또는 "모듈"필드를 비우고 ( "없음"으로 표시) 관리 대상 객체 서브 클래스를 표시 할 수 있습니다 @objc(classname)( https://stackoverflow.com/a/31287260/1187415 참조 ).


비고 : 이 답변은 원래 Xcode 6 용으로 작성된 것입니다.이 문제와 관련하여 다양한 Xcode 7 베타 릴리스에서 일부 변경 사항이있었습니다. 그것은 많은 upvotes와 그것에 대한 링크로 받아 들여진 대답이므로 현재 Xcode 7 최종 버전의 상황을 요약하려고했습니다.

나는 내 자신의 "연구"를 수행 하고이 질문과 비슷한 질문 CoreData에 대한 모든 대답을 읽었습니다 . 경고 : 이름이 지정된 클래스를로드 할 수 없습니다 . 따라서 속성을 구체적으로 나열하지 않더라도 저작자 표시가 모두에게 적용됩니다.


Xcode 6에 대한 이전 답변 :

핵심 데이터 관리 객체 하위 클래스 구현에 설명 된대로 모델 엔터티 관리자의 클래스 필드에서 엔터티 클래스 이름 앞에 모듈 이름 (예 : "MyFirstSwiftApp.User")을 접두사로 추가해야합니다.


부수적으로. 나는 같은 문제가 있었다. 그리고 내가해야 할 일은 @objc(ClassName)내 수업 파일 에 추가 하는 것입니다.

예:

@objc(Person)
class Person { }

그리고 그것은 내 문제를 해결했습니다.


이 질문에 대한 대답은 같은 문제를 해결하는 데 도움이되었지만 다른 사람들에게 도움이 될 것이라는 경고가있었습니다. 프로젝트 (모듈) 이름에 공백이 있으면 공백을 밑줄로 바꿔야합니다. 예를 들면 다음과 같습니다.

엔터티 : MyEntity 클래스 : My_App_Name.MyClass


모듈 을 제거하십시오 :

여기에 이미지 설명을 입력하십시오


Depending if you are running as App vs Tests the issue can be that the app is looking for <appName>.<entityName> and when it's running as test it's looking as <appName>Tests.<entityName>. The solution I use at this time (Xcode 6.1) is to NOT fill the Class field in the CoreData UI, and to do it in code instead.

This code will detect if you are running as App vs Tests and use the right module name and update the managedObjectClassName.

lazy var managedObjectModel: NSManagedObjectModel = {
    // The managed object model for the application. This property is not optional...
    let modelURL = NSBundle.mainBundle().URLForResource("Streak", withExtension: "momd")!
    let managedObjectModel = NSManagedObjectModel(contentsOfURL: modelURL)!

    // Check if we are running as test or not
    let environment = NSProcessInfo.processInfo().environment as [String : AnyObject]
    let isTest = (environment["XCInjectBundle"] as? String)?.pathExtension == "xctest"

    // Create the module name
    let moduleName = (isTest) ? "StreakTests" : "Streak"

    // Create a new managed object model with updated entity class names
    var newEntities = [] as [NSEntityDescription]
    for (_, entity) in enumerate(managedObjectModel.entities) {
        let newEntity = entity.copy() as NSEntityDescription
        newEntity.managedObjectClassName = "\(moduleName).\(entity.name)"
        newEntities.append(newEntity)
    }
    let newManagedObjectModel = NSManagedObjectModel()
    newManagedObjectModel.entities = newEntities

    return newManagedObjectModel
}()

If you are using a hyphen in your project name like "My-App" then use an underscore instead of the hyphen like "My_App.MyManagedObject". In general, look at the name of the xcdatamodeld file and use the same prefix as in that name. I.e. "My_App_1.xcdatamodeld" requires the prefix "My_App_1"


This may help those experiencing the same problem. I was, with Swift 2 and Xcode 7 beta 2.

The solution in my case was to comment out @objc(EntityName) in EntityName.swift.


I had the same warning, though my app appeared to run fine. The problem was that when running Editor > Create NSManagedObject Subclass on the last screen I used the default Group location, with no Targets displayed or checked, which saved the subclass in the top MyApp directory where MyApp.xcodeproj was located.
The warning went away when I instead changed the Group to be in the MyApp subfolder and checked the MyApp target.


The above answers were helpful. This quick sanity check may save you some time. Go into Project > Build Phases > Compile Sources and remove your xcdatamodeld and your model files with the "-" button, and then add them right back with the "+" button. Rebuild -- that may take care of it.


By the way be carful what you add as a prefix: My App is called "ABC-def" and Xcode has converted the "-" into a "_".

To be safe look into the finder, find your project files and see what it says for your data model (for example "ABC_def.xcdatamodeld") and use what is written there EXACTLY!!!


The above answers helped me to solve different issue connected with Objective-C (maybe it will help someone):

엔터티 이름을 리팩토링 한 경우 "유틸리티 패널"에서 "클래스"도 변경해야합니다.


위의 답변이 도움이되었지만 누군가에게 도움이 될 수 있습니다. 나처럼 당신이 그들을하고 여전히 문제가있는 경우, 단순히 '프로젝트를 청소'를 기억하십시오. XCode8의 경우 제품> 청소 그런 다음 다시 실행하십시오.


Xcode 7에서 엔티티와 클래스 이름은 동일 할 수 있지만 Codegen은 클래스 정의 여야합니다. 이 경우 경고 등이 없습니다. 여기에 이미지 설명을 입력하십시오.

참고 URL : https://stackoverflow.com/questions/25076276/unable-to-find-specific-subclass-of-nsmanagedobject

반응형