1

여러 속성이있는 코어 데이터 엔티티가 있는데 하나의 속성에 모든 객체의 목록이 필요합니다.엔티티에서 선택된 속성을 가져 오는 중

 let appDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate 
     let context:NSManagedObjectContext = appDel.managedObjectContext! 

     let sortDesc = NSSortDescriptor(key: "username", ascending: true) 

     let fetchReq = NSFetchRequest(entityName: "Identities") 
     fetchReq.sortDescriptors = [sortDesc] 
     fetchReq.valueForKey("username") 

     let en = NSEntityDescription.entityForName("Identities", inManagedObjectContext: context) 

     userList = context.executeFetchRequest(fetchReq, error: nil) as [Usernames] 

을하지만이 나에게 NSException 오류를 제공하고, 왜 알아낼 수 없습니다, 또는 나는이 작업을 수행하는데있어 방법 : 내 코드는 다음과 같습니다. 내가 NSFetchRequest 클래스 설명을 읽었지만 그것에서 많은 의미를 만들 수 없습니다.

의견을 보내 주시면 감사하겠습니다.

편집 : Bluehound에서 팁 후 나는이 내 코드를 변경 :

var userList = [Model]() 
@IBAction func printUsers(sender: AnyObject) { 
    let appDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate 
    let context:NSManagedObjectContext = appDel.managedObjectContext! 

    let sortDesc = NSSortDescriptor(key: "friendID", ascending: true) 

    let fetchReq = NSFetchRequest(entityName: "Identities") 
    fetchReq.sortDescriptors = [sortDesc] 
    fetchReq.propertiesToFetch = ["friendID"] 

    let en = NSEntityDescription.entityForName("Identities", inManagedObjectContext: context) 

    userList = context.executeFetchRequest(fetchReq, error: nil) as [Model] 

    println(userList) 

} 

는 런타임 오류가 사라지고하지만 내가 변환하는 방법을 잘 모르겠어요 때문에 작동하는지 나는 아직도 모른다 문자열 목록에 나열하십시오.

항상 그렇듯이 제안을 환영합니다.

+0

'valueForKey' 대신'NSFetchRequest'의'propertiesToFetch' 속성을 사용하십시오. – Ian

+0

@Bluehound NSPropertyDescription을 초기화하는 데 어려움이 있습니다. – martin

+0

println (userList)의 출력은 어떻게 생깁니 까? – pbasdf

답변

3

는 두 가지 가능성이있다 : 당신은 정상적인 요청 가져 발행하고 map()를 사용하여 결과에서 원하는 속성을 포함하는 배열, 을 추출 할 수 있습니다 :

let fetchReq = NSFetchRequest(entityName: "Identities") 
fetchReq.sortDescriptors = [sortDesc] 

var error : NSError? 
if let result = context.executeFetchRequest(fetchReq, error: &error) as? [Model] { 
    let friendIDs = map(result) { $0.friendID } 
    println(friendIDs) 
} else { 
    println("fetch failed: \(error!.localizedDescription)") 
} 

스위프트 2 :

let fetchReq = NSFetchRequest(entityName: "Identities") 
fetchReq.sortDescriptors = [sortDesc] 

do { 
    let result = try context.executeFetchRequest(fetchReq) as! [Model] 
    let friendIDs = result.map { $0.friendID } 
    print(friendIDs) 
} catch let error as NSError { 
    print("fetch failed: \(error.localizedDescription)") 
} 

또는 resultType.DictionaryResultTypepropertiesToFetch으로 설정하십시오. desired 속성.

let fetchReq = NSFetchRequest(entityName: "Identities") 
fetchReq.sortDescriptors = [sortDesc] 
fetchReq.propertiesToFetch = ["friendID"] 
fetchReq.resultType = .DictionaryResultType 

var error : NSError? 
if let result = context.executeFetchRequest(fetchReq, error: &error) as? [NSDictionary] { 
    let friendIDs = map(result) { $0["friendID"] as String } 
    println(friendIDs) 
} else { 
    println("fetch failed: \(error!.localizedDescription)") 
} 

스위프트 2 : 두 번째 방법은 지정된 속성 데이터베이스로부터 페치되는 장점을 갖는다

let fetchReq = NSFetchRequest(entityName: "Identities") 
fetchReq.sortDescriptors = [sortDesc] 
fetchReq.propertiesToFetch = ["friendID"] 
fetchReq.resultType = .DictionaryResultType 

do { 
    let result = try context.executeFetchRequest(fetchReq) as! [NSDictionary] 
    let friendIDs = result.map { $0["friendID"] as! String } 
    print(friendIDs) 
} catch let error as NSError { 
    print("fetch failed: \(error.localizedDescription)") 
} 

이때 페치 요청 딕셔너리의 배열을 반환 전체 관리 대상이 아닙니다.

그것은 결과는 관리 오브젝트 컨텍스트 저장되지 않은 변경이 아직 포함되지 않는 단점 (.DictionaryResultTypeincludesPendingChanges: 사용시 암시 false로 설정된다)를 갖는다.

+0

"Entities"라는 엔티티 이름과 관리 대상 하위 클래스 "Model"의 이름을 질문의 코드에서 가져 왔습니다. 일반적으로 둘 모두에 동일한 이름을 사용합니다. –

+0

다시 한 번 감사드립니다 마틴, 당신은 결코 실망하지 않습니다. 네, 이름이 최적이 아니라는 것을 압니다. 저는 오래전에 만든 "테스트 프로젝트"일뿐입니다. – martin

관련 문제