Realm and indexes on properties - realm

CONTEXT
Realm does not support indices on relationship properties (objects). https://realm.io/docs/objc/latest/#indexed-properties
If you try, it'll throw an error.
We have a situation, where we need to query a model's relationship and another property.
Typically you would do this by having a covering index across (foreign_id, property), but this does not appear to be possible in Realm (yet?)
For example
#interface Book : RLMObject
#property NSNumber<RLMInt> * page;
#end
#interface Page : RLMObject
#property Book * book;
#property NSNumber<RLMInt> * line;
#end
[Page objectsInRealm:realm where:#"book.uuid = %# AND page.line = %#", uuid, #1];
QUESTION
What is the best way to set up indices so that the query above is optimal?
Are relationships already indexed?
Or Do I create another property on Page, called book_uuid, and index on that?
Cheers

Realm doesn't really cater to the foreign key mechanism of relational databases, so it's easier to get out of that mindset when designing your data model.
In this case, I think it would be more appropriate that your Book model stores an array of all of your pages (sort of an inverse to the foreign key concept), which you can use to initially filter the pages to just that book, and to then query for the specific page line:
#interface Page : RLMObject
#property NSInteger line;
#end
RLM_ARRAY_TYPE(Page)
#interface Book : RLMObject
#property RLMArray<Page *><Page> *pages;
#end
Book *book = [[Book allObjects] firstObject];
Page *page = [[book.pages objectsWhere:#"line = %#", #1] firstObject];
As long as you've marked line as an indexed property, this should work very quickly in theory. But since you've mentioned you've got thousands of page lines, I'd be curious to see what the real-world performance of this would be.

Related

Provide a Converter for data-binding by defining a pair of SerializableFunction objects

In Vaadin 8 Framework, and Vaadin 10 Flow, the data-binding capability lets us provide a Converter to mediate between the widget’s expected data type (such as String for a TextField) and the data type of the backing bean property (such as Integer number).
In this example, the built-in Converter implementation StringToIntegerConverter is used.
binder
.forField( this.phaseField )
.withConverter(
new StringToIntegerConverter( "Must enter an integer number" )
)
.bind( Panel::getPhase , Panel::setPhase ) ;
But what about defining a Converter for other types? How can I easily define a short-and-sweet Converter? For example, a String-to-UUID converter. I want to show the canonical 36-character hex string in a TextField, and going the other direction, parse that string back into a UUID.
// String to UUID
UUID uuid = UUID.fromString( myString ) ;
// UUID to String
String myString = uuid.toString() ;
I see that Binder.BindingBuilder offers the pair of methods withConverter that both take a pair of SerializableFunction objects.
Binder.BindingBuilder::withConverter(SerializableFunction<TARGET,NEWTARGET> toModel, SerializableFunction<NEWTARGET,TARGET> toPresentation)
Binder.BindingBuilder::withConverter(SerializableFunction<TARGET,NEWTARGET> toModel, SerializableFunction<NEWTARGET,TARGET> toPresentation, String errorMessage)
➥ So how do I define the pair of SerializableFunction objects/classes?
I noticed that this interface lists a known subinterface ValueProvider<SOURCE,TARGET>. That looks familiar, and I have a hunch it is the key to easily defining a short simple converter. But I do not quite comprehend the syntax with lambdas and all that is going on here.
I am not asking how to write a class implementing Converter. I am asking how to write the pair of SerializableFunction arguments to pass to the Binder.BindingBuilder::withConverter methods listed above as bullet items.
Quoting that JavaDoc:
Interface Binder.BindingBuilder<BEAN,TARGET>
…
withConverter
default <NEWTARGET> Binder.BindingBuilder<BEAN,NEWTARGET> withConverter(SerializableFunction<TARGET,NEWTARGET> toModel, SerializableFunction<NEWTARGET,TARGET> toPresentation)
Maps the binding to another data type using the mapping functions and a possible exception as the error message.
The mapping functions are used to convert between a presentation type, which must match the current target data type of the binding, and a model type, which can be any data type and becomes the new target type of the binding. When invoking bind(ValueProvider, Setter), the target type of the binding must match the getter/setter types.
For instance, a TextField can be bound to an integer-typed property using appropriate functions such as: withConverter(Integer::valueOf, String::valueOf);
Type Parameters:
NEWTARGET - the type to convert to
Parameters:
toModel - the function which can convert from the old target type to the new target type
toPresentation - the function which can convert from the new target type to the old target type
Returns:
a new binding with the appropriate type
Throws:
IllegalStateException - if bind has already been called
You can do it by passing two lambda expressions to withConverter, so something like this:
binder.forField(textField)
.withConverter(text -> UUID.fromString(text), uuid -> uuid.toString())
.bind(/* ... */);
If you need a more complicated conversion, then the right-hand side of the lambda can be surrounded with brackets, e.g.
binder.forField(textField).withConverter( text -> {
if ( text == null ) {
return something;
} else {
return somethingElse;
}
}, uuid -> { return uuid.toString(); } )
.bind(/* ... */);
If you need your converter multiple times, I recommend creating a separate class implementing interface com.vaadin.data.Converter. However, using lambdas is possible, too, as you already know (see answer of #ollitietavainen). But this is not Vaadin specific, it's a Java 8+ feature you can read about e.g. here. Basically, you can use lambdas whereever an object implementing an interface with only one method is required.

How to handle null value in realm.io?

from what I see if the value is nil for a property it always throws exception. sometimes i cannot simply set a '' empty string as nil, so what's the solution in realm? thanks.
Null is now fully supported.
OLD answer:
Supporting nil/NULL is on the roadmap.
Until then there are two workarounds:
Add a separate property to indicate if your property is nil.
#interface IntObject : RLMObject
#property NSInteger myProp;
#property boolean myPropIsNil;
#end
Wrap your property in an object:
Object properties (links), can be nil though. So if you need a nullable int property, for example, you can wrap it in a new Realm model, like this:
#interface IntObject : RLMObject
#property NSInteger myProp;
#end
Then anytime you want to have an optional "int" property in your models, you can write this:
#interface MyModel : RLMObject
#property IntObject *optionalMyProp;
#end

Inverse relation in realm

Let's assume two tables Boxand Item. Box may have many items, one item have only one box. I would like to fetch all items which have box is in given array. How could I do that? In CD I would do it by predicate and property in Item class which stands for connection to Box.
I am using version 0.81
UPDATE (10-27-2014)
Bidirectional relationships are now supported. See Realm's docs: http://realm.io/docs/cocoa/latest#inverse-relationships
ORIGINAL ANSWER
Bidirectional relationships must be explicitly linked at this time. Here's an example:
#class Box;
#interface Item : RLMObject
#property Box *box;
#end
RLM_ARRAY_TYPE(Item);
#interface Box : RLMObject
#property RLMArray<Item> *items;
#end
...
Item *item = [[Item alloc] init];
Box *box = [[Box alloc] initWithObject:#[#[item]]];
item.box = box;
We have plans to simplify this pattern in the future.
This answer was taken from GitHub

KVC valueForKey return a __NSCFConstantString instead a __NSCFString

I use KVC in my projects.
And, in one of my classes, I wrote the property :
#property ( nonatomic, strong ) NSString *notes;
I want to put a NSString object in that property :
And before setting the value, I want to test the class name of the destination.
a = [ newContainer valueForKey:#"notes"];
if( a != nil && ![ b isKindOfClass:[ a class ] ] )
// here b is the new NSString value
The result is that xcode indicates that the classes aren't the same !
(gdb) po [ b class ]
__NSCFString
(gdb) po [ a class ]
__NSCFConstantString
I read that is not very important and that __NSCFConstantString is a private subclass of NSString.
But, in my case, I need to check all properties of my object before updating it.
And I don't want to had in my code :
// OK, classes aren't the same ...
// ---- BUT WE MUST test it again to know if a is a NSString and b a subclass of NSString or anything else ...
beurk !
Is anyone have the same problem ?
Thanks a lot for your help !
Three points:
1- You should check against [NSString class], the publicly exposed class of your property, not against the class of the current value of your property.
Imagine what happens when you check against the value class, instead of the property class: after setting your property to a NSMutableString, which is a perfect instance of NSString, you could not any longer set it to a regular NSString (since NSString is not a subclass of NSMutableString). Your current problem is a variant of the one described in this paragraph, which may be easier to understand.
2- The test should be done in the class that owns the property, not outside as you are doing now. Because only that class is entitled to know about the type of object it accepts.
3- So. Use the standard validateValue:forKey:error: method, which is your friend here. This method would be implemented by the class, and it would make sure notes is a NSString. Outside of the class, you would not check the type of the value directly, but ask the container class to validate it.
And voilà !

Subclassing NSString

Using WSDL2ObjC I am getting lot of classes which are subclasses of NSString.
I am finding it troublesome to initialize the NSString value of any object of those classes.
Say my class looks like this :
#interface mClass ; NSString {
int value;
}
Now in my code I would like to use objects of mClass as both NSString and also want to use its attribute value which is an integer.
How can I do that?
I am trying to use code like this
mClass *obj = [[mClass alloc] initWithString:#"Hello"];
But it's showing me an error saying I am using an abstract object of a class , I should use concrete instance instead.
If you really need make NSString subclass you should override 3 methods:
- (instancetype)initWithCharactersNoCopy:(unichar *)characters length:(NSUInteger)length freeWhenDone:(BOOL)freeBuffer;
- (NSUInteger)length;
- (unichar)characterAtIndex:(NSUInteger)index;
For example:
MyString.h
#interface MyString : NSString
#property (nonatomic, strong) id myProperty;
#end
MyString.m
#interface MyString ()
#property (nonatomic, strong) NSString *stringHolder;
#end
#implemenation MyString
- (instancetype)initWithCharactersNoCopy:(unichar *)characters length:(NSUInteger)length freeWhenDone:(BOOL)freeBuffer {
self = [super init];
if (self) {
self.stringHolder = [[NSString alloc] initWithCharactersNoCopy:characters length:length freeWhenDone:freeBuffer];
}
return self;
}
- (NSUInteger)length {
return self.stringHolder.length;
}
- (unichar)characterAtIndex:(NSUInteger)index {
return [self.stringHolder characterAtIndex:index];
}
#end
It might be smarter to use a wrapper class that internally uses NSStrings to do whatever operations or manipulations you are trying to do. However this will cause you to need to overload any functionality of NSString you want (such as getting the length of the string).
Or, you could create a category of NSString (found right next to Objective-C class in the new file window). This allows you to add any properties or methods that you wish to be "added" to the NSString class. Now just import this category wherever you wish to use it and you will have all of your custom functions available on any NSStrings objects.
Do you really need to subclass NSString? It’s a class cluster, which (apart from other things) means it’s hard to subclass. There’s a good post by Mike Ash on subclassing class clusters. If you didn’t know that class clusters existed you are probably new to Cocoa and in that case the best short answer is don’t try to subclass class clusters.
There’s also previous questions about subclassing NSString here on Stack Overflow. Next time you might want to search a bit before asking a new question.

Resources