2017-09-20 2 views
2

.유형의 'NSKnownKeysDictionary1'()에 '을'값을 캐스팅 할 수 없습니다() 나는 내가 <em>JSON</em>에 대한 직렬화 사용할 수있는 <em>사전</em>에 내 <em>NSManagedObject</em> 변환을 시도하고있어

func fetchRecord() -> [Record] { 

     let fetchRequest = NSFetchRequest<Record>(entityName:"Record") 
     let context = PersistenceService.context 

     fetchRequest.resultType = .dictionaryResultType 

     do { 
      records = try context.fetch(Record.fetchRequest()) 

     } catch { 
      print("Error fetching data from CoreData") 
     } 
     print(records) 
     return records 
} 
나는이 질문에 loked 한

: How to convert NSManagedObject to NSDictionary하지만 그 방법은 광산 매우 다른 나타납니다. 나는 또한이 질문에서 제공된 방법을 시도했다 : CoreData object to JSON in Swift 3. 그러나 나는

가 'iOSTest01.Record'에 유형의 가치 'NSKnownKeysDictionary1'(0x108fbcaf8)를 캐스팅 할 수 없습니다이 오류를 수신하고하는 것은 (0x1081cd690) $

나는 해결책을 찾을 수 없습니다 .

여기까지 오류가 언급되었지만 Core Data: Could not cast value of type 'MyType_MyType_2' to MyType입니다. 그러나 문제가 해결되는 방법이 없습니다. 누구든지 나를 스위프트 해결 방법을 제공 할 수 있을까요?

var record: Record! 
var records = [Record]() 

기록 + CoreDataClass :

public class Record: NSManagedObject { 

} 

기록 + CoreDataProperties :

extension Record { 

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Record> { 
     return NSFetchRequest<Record>(entityName: "Record") 
    } 

    @NSManaged public var name: String? 

} 
,536 나는 다음과 같은 추가 아래

업데이트

는 설명을 돕기 위해

여기에 records이 정의되어 있습니다.

+0

'레코드'는 어디에 정의되어 있습니까? -'resultType = .dictionaryResultType'을 사용하면 인출 요청은 * [Record]'와 호환되지 않는 * 사전 배열을 반환합니다. –

+0

질문에 대한 내 업데이트를 참조하십시오. – Chace

+0

레코드 개체 배열이나 사전 배열을 원하십니까? –

답변

3

다음 두 가지를 수행해야 페치 요청 에서 사전의 배열을 얻기 위해 :

  • 설정 fetchRequest.resultType = .dictionaryResultType (이미 그랬던 것처럼), 및
  • NSFetchRequest<NSDictionary>로 가져 오기 요청을 선언 NSFetchRequest<YourEntity> 대신.

예 :

let fetchRequest = NSFetchRequest<NSDictionary>(entityName:"Event") 
fetchRequest.resultType = .dictionaryResultType 

// Optionally, to get only specific properties: 
fetchRequest.propertiesToFetch = [ "prop1", "prop2" ] 

do { 
    let records = try context.fetch(fetchRequest) 
    print(records) 
} catch { 
    print("Core Data fetch failed:", error.localizedDescription) 
} 

지금 records이 유형 [NSDictionary]을 가지며 페치 객체와 표현 사전 배열을 포함 할 것이다.

+0

고맙습니다. 제 데이터가 이제 사전으로 인쇄됩니다. 그러나'NSDictionary' 대신'Record' 클래스를 사용하지 않아서 어떻게 데이터를 표시하는지 변경되었습니다.이전과 같이 내 데이터를 표시하는 가장 좋은 방법은 무엇입니까? – Chace

+1

@Chace : 별도의 가져 오기 요청을 사용합니다. 하나는 (NSFetchedResultsController를 사용하여) 테이블 뷰에 데이터를 표시하고 다른 하나는 데이터를 내보내는 데 사용됩니다. –