领域中的可选整数

Optional Int in Realm

我正在尝试在 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 不支持作为 Optionalhttps://twitter.com/realm/status/656621989583548416。那是来自 Realm 的推特,所以这就是我感到困惑的原因。 Optional Int 支持还是不支持?

来自 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 以及 Int 的所有尺寸版本(Int8Int16Int32Int64).

更新:

Realm 在 Tweet 中提到的可选整数只是关于 RealmOptional 使用 Int[的大小版本实现可选数值的方法的错误修复] =31=]

According 来自 Realm 的人,如果你想在 Realm 对象中有可选的数值,你仍然必须使用 RealmOptional。您不能像其他 Optional 类型一样简单地使用它。

所以dynamic var reps: Int?将不起作用。

在objective c的情况下,我们可以像这样使用optional

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

有关更多信息,您还可以查看此 link: https://realm.io/blog/realm-objc-swift-0-96-0/