xcode 如何在 swift 'AnyObject' 中从 coredata 字典中打印出值没有名为 'username 的成员?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26458209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 05:55:52  来源:igfitidea点击:

How to print out value from coredata dictionary in swift 'AnyObject' does not have a member named 'username?

xcodeswift

提问by Rolando

I am trying to print out the value "username" from my coredata entity.

我试图从我的核心数据实体中打印出值“用户名”。

var request = NSFetchRequest(entityName: "Users")

request.returnsObjectsAsFaults = false

var results = context.executeFetchRequest(request, error: nil)

if (results?.count > 0) {

    for result: AnyObject in results! {
        println(result.username)
    }
}

The line println(result.username) is giving me a compile error of 'AnyObject' does not have a member named 'username'.

行 println(result.username) 给了我一个编译错误“AnyObject”没有名为“username”的成员。

回答by Martin R

You have to cast the array of managed object to the correct type:

您必须将托管对象数组强制转换为正确的类型:

for result in results! as [Users] {
    println(result.username)
}

This assumes that you have created a managed object subclass for the "Users" entity.

这假设您已经为“用户”实体创建了一个托管对象子类。

You should also distinguish whether executeFetchRequest()returned nil(i.e. the fetch request failed), or 0(i.e. no objects found), and use the errorparameter:

您还应该区分是executeFetchRequest()返回nil(即获取请求失败)还是0(即未找到对象),并使用error参数:

var error : NSError?
if let results = context.executeFetchRequest(request, error: &error) {
    if (results.count > 0) {
        for result in results as [Users] {
            println(result.username)
        }
    } else {
        println("No Users")
    }
} else {
    println("Fetch failed: \(error)")
    // Handle error ...
}

Update for Swift 2/Xcode 7with try/catch error handling:

使用 try/catch 错误处理更新Swift 2/Xcode 7

do {
    let results = try context.executeFetchRequest(request) as! [Users]
    if (results.count > 0) {
        for result in results {
            print(result.username)
        }
    } else {
        print("No Users")
    }
} catch let error as NSError {
    // failure
    print("Fetch failed: \(error.localizedDescription)")
}

Note that the forced cast as! [Users]is acceptable here. The returned objects are always instances of the corresponding class as configured in the Core Data model inspector, otherwise you have a programming errorwhich should be detected early.

请注意,as! [Users]这里可以接受强制转换。返回的对象始终是 Core Data 模型检查器中配置的相应类的实例,否则您应该及早检测到编程错误

回答by sean woodward

Martin's answerdefinitely lets you access the properties of your object, but the cast is forced. Like it or not, Swift's strong type system is the future. When returning results from a fetch request, you might consider testing for the type.

Martin 的回答绝对可以让您访问对象的属性,但强制转换。不管喜欢与否,Swift 的强类型系统是未来。从获取请求返回结果时,您可能会考虑测试类型。

func executeFetchRequestT<T:AnyObject>(request:NSFetchRequest, managedObjectContext:NSManagedObjectContext, error: NSErrorPointer = nil) -> [T]? {
    var localError: NSError? = nil

    if let results:[AnyObject] = managedObjectContext.executeFetchRequest(request, error: &localError) {
        if results.count > 0 {
            if results[0] is T {
                let casted:[T] = results as [T]
                return .Some(casted)
            }

            if error != nil {
                error.memory = NSError(domain: "error_domain", code: 0, userInfo: [NSLocalizedDescriptionKey: "Object in fetched results is not the expected type."])
            }

        } else if 0 == results.count {
            return [T]() // just return an empty array
        }
    }

    if error != nil && localError != nil {
        error.memory = localError!
    }

    return .None
}

Using this approach you can type your results and get an error if the type is incorrect.

使用这种方法,您可以输入结果,如果类型不正确,则会出现错误。

var fetchError:NSError? = nil

if let results:[Users] = executeFetchRequestT(fetchRequest, managedObjectContext: managedObjectContext, error: &fetchError) {

    for user in results {
        // access the results with confidence of the correct type
    }

} else {

    // should have an error condition, handle it appropriately
    assertFailure("something bad happened")

}

回答by brokenrhino

Change your for loop to this

将您的 for 循环更改为此

     for result: AnyObject in results! {

            if let user: AnyObject = result.valueForKey("username") {

                println(user)

            }

        }

The fix is using valueForKey("String")

修复是使用 valueForKey("String")