ios - 在 Realm 中查询(使用 Swift)

标签 ios types swift realm

我在玩 realm.io。我写了几个对象,现在我想查询它们。我的数据类:

class Sample : RLMObject {
    dynamic var sampleKey : String = ""
}

和我的查询代码

@IBAction func readLocalRecord(sender: UIButton) {

    let s : NSString = NSString.stringWithString("sampleKey == SampleValue")
    let p : NSPredicate = NSPredicate(format: "sampleKey = %@", argumentArray: NSArray(object: NSString.stringWithString("SampleValue")))

    // the following throws exception, that I cannot catch in Swift:
    //   'Unsupported predicate value type', reason: 'Object type any not supported'
    let r = Sample.objectsWithPredicate(p)
}

Webside 和 RLMObject 的标题表明我应该可以说 Sample.objectsWhere("sampleKey = 'SampleValue'") (或类似的),但是 objectsWhere 给出了一个编译错误,提示函数不存在,并且没有自动完成功能。所以我尝试使用 objectsForPredicate 代替,但这表示类型“any”(通过标题挖掘,我发现这等于 Realm 术语中 ObjC 的“id”类型)。我在这里做错了什么?我尝试非常明确,确保使用 NSString 而不是 String 和 NSArray 而不是 Array,但仍然有一些东西被解释为“id”而不是特定类型。

有什么建议吗?

干杯

-尼克

最佳答案

你的代码对我来说在 Xcode 6 beta 5 上运行良好。顺便说一下,你不需要在这里显式使用 NSArrayNSString - Swift 将桥接到目标 - c 类型给你。以下对我有用并打印出我希望看到的对象:

import Realm

class Sample : RLMObject {
    dynamic var sampleKey : String = ""
}

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func readLocalRecord() {

        // create some sample records
        RLMRealm.defaultRealm().beginWriteTransaction()
        var s = Sample()
        s.sampleKey = "Testing"
        RLMRealm.defaultRealm().addObject(s)
        var s2 = Sample()
        s2.sampleKey = "SampleValue"
        RLMRealm.defaultRealm().addObject(s2)
        RLMRealm.defaultRealm().commitWriteTransaction()

        let p : NSPredicate = NSPredicate(format: "sampleKey = %@", argumentArray: [ "SampleValue" ])

        let r = Sample.objectsWithPredicate(p)
        println(r)
    }

    func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {

        readLocalRecord()

        return true
    }
}

输出是:

RLMArray <0x7fe8241218c0> (
    [0] Sample {
        sampleKey = SampleValue;
    }
}

请注意,Realm 的 objectsWithPredicate 方法返回一个 Realm 数组,而不是一个普通的数组。

关于ios - 在 Realm 中查询(使用 Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25198509/

相关文章:

ios - 将 NSDate 转换为 NSString 以保存在 NSMutableArray 中

c++ - const 引用的类型是什么?

c++ - 我如何在 C++ 中去除一个类型的所有信息?

swift - 显示结构中数字的舍入值的最佳方法

ios - 在 viewDidLoad 中移动图像

ios - 站点使用 iOS 信任的证书签名

swift - 在 Swift 中连接 SQLite 数据库

ios - Coredata 链接关系

ios - 无法更改翻转的 UIImage 图像 Swift 2 iOS 的 tintColor

sql - ORDER BY 取决于列类型