Search code examples
iosnsdatarealmnsnull

realm crash when NSData property is nil


I have a Realm class defined with "image" property of type NSData. I have set the default value for "image" in +defaultPropertyValues method's NSDictionary return value as

@"image":[NSNull null]. This is to indicate no image value has been set.

However, program crashes when saving an Realm object with the following error:

[NSNull UTF8String]: unrecognized selector sent to instance 0x10abe9ce0

Can you advise if nil value is not allowed for NSData property in Realm Object. If so, is there a different way to represent empty NSData property.

The issue doesn't exist when a non-nil NSData value is set.

Thank you in advance

UPDATE: Code:

Item.h
@interface UploadImage : RLMObject
  @property uploadImage:NSData
@end

Item.m
+ (NSDictionary *)defaultPropertyValues
{
  return @{@"uploadImage":[NSNull null]...};
}

Error occurs when uploadImage is set to nil or takes default value from NSDictionary. Workaround I used was to create a 0 byte NSData using ["" dataUsingEncoding:NSUTF8StringEncoding]


Solution

  • Currently only one kind of property can be nil/NULL, and that is the RLMObject property. Optional (nullable) properties is something that has high priority, but for the moment we recommend either of these two workaraounds:

    1. Define an RLMObject subclass with the NSData (e.g.) as its sole property. This is then nullable.
    2. Add a separate boolean property that keeps track of whether the NSData one is nil or not.

    Read more here:

    How to handle null value in realm.io?