realm crash when NSData property is nil

2.1k views Asked by At

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]

2

There are 2 answers

0
Gusutafu On BEST ANSWER

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?

0
Bruno Paulino On

You can initialize the NSData property and check if the length is 0:

let data = NSData()
if data.length == 0 {
  println("handle like nil value")
} else {
  println("Do what you want")
}