Realm中的可选整数

29

我正尝试在Realm中使用Optional Int,但是遇到了一个我认为是旧错误。

代码

dynamic var reps: Int? = nil

错误

'Property cannot be marked dynamic because its type cannot be represented in Objective-C'

我正在使用Realm 0.96.1和XCode 7.1

我知道在Realm文档中,它说Int不支持作为Optional,但是https://twitter.com/realm/status/656621989583548416。这是来自Realm的推特,所以我很困惑。Optional Int是否被支持了还是没有?


你更新了 Realm 吗?另外,你在使用 Cocoapods 吗?你确定你正在使用 0.96.1 版本吗? - Charles Truluck
是的,我正在使用CocoaPods。Realm 0.96.1和RealmSwift 0.96.1。 - Cody Weaver
尝试使用Int16、32或64。我正在查看文档,它说它们只支持0.96.1版本中的这些内容。你正在使用Swift 2.0分支,对吗? - Charles Truluck
请参考 https://dev59.com/25Dea4cB1Zd3GeqPcHul 了解为什么 Int? 不适用于可选属性。 - bdash
2个回答

51

来自 Realm 文档:

StringNSDateNSData 属性可以使用标准的 Swift 语法声明为可选或非可选。

可选数字类型使用 RealmOptional 声明:

class Person: Object {
    // Optional string property, defaulting to nil
    dynamic var name: String? = nil

    // Optional int property, defaulting to nil
    // RealmOptional properties should always be declared with `let`,
    // as assigning to them directly will not work as desired
    let age = RealmOptional<Int>()
}

let realm = try! Realm()
try! realm.write() {
    var person = realm.create(Person.self, value: ["Jane", 27])
    // Reading from or modifying a `RealmOptional` is done via the `value` property
    person.age.value = 28
}

RealmOptional 支持 IntFloatDoubleBool,以及所有大小版本的 IntInt8Int16Int32Int64)。

更新:

在 Realm 的推文中提到的可选整数只是有关修复使用带有大小版本的Int实现可选数值的RealmOptional的错误的内容。

根据来自 Realm 团队的说法,如果您想在 Realm 对象中具有可选数字值,则仍然需要使用 RealmOptional,不能像其他可选类型一样简单地使用它。

因此,dynamic var reps: Int? 将无法工作。


我看到文档中提到了这一点,但我认为在0.96.1版本中也支持Int。我认为那些文档是针对0.96版本的。 - Cody Weaver
我刚刚更新到了RealmSwift 0.96.2,但是当你试图将Int定义为Optional时,它仍然会出现与你描述的相同的错误消息。在0.96.1版本的发布说明中,它说“修复了在Swift中使用可选的Int16/Int32/Int64属性时崩溃的问题。”他们只称其为一个bug fix,而不是一个新功能。在我看来,添加“真正”的Optional Int将是一个新功能。所以我想你仍然需要使用RealmOptional - joern
我刚刚从 Realm 官方那里得到确认,即“RealmOptional”仍然必须用于可选数值类型:https://twitter.com/realm/status/658795663254253568。 - joern
有人能解释一下为什么 Realm 必须引入自己的类型,无法插入到原始可选项中吗? - Paweł Brewczynski
为什么不声明为let?如何更改它的值? - JBarros35
@JBarros35,代码注释中已经有解释了;-) 我是从 Realm 文档中获取的。 - joern

1
在Objective-C中,我们可以像这样使用可选项。
Optional numbers can be stored using an NSNumber * property which is tagged with the type of the number.

You can use NSNumber <RLMInt> *, NSNumber<RLMBool> *, NSNumber<RLMFloat> *, and NSNumber<RLMDouble> *.

请参考以下示例代码。
@interface OptionalTypes : RLMObject
@property NSString *optionalString;
@property NSString *requiredString;
@property NSData *optionalData;
@property NSDate *optionalDate;
@property NSNumber<RLMInt> *optionalInt;
@property NSNumber<RLMBool> *optionalBool;
@property NSNumber<RLMFloat> *optionalFloat;
@property NSNumber<RLMDouble> *optionalDouble;
@end
@implementation OptionalTypes
+ (NSArray *)requiredProperties {
    return @[@"requiredString"];
}
@end

如果您需要更多信息,您也可以查看此链接: https://realm.io/blog/realm-objc-swift-0-96-0/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接