I made a protocol called Synchronizable and I have some of my Realm objects conformed to this protocol.
Such as :
class Comment : Object, Synchronizable {
// ...
}
I want to query all of local Realm objects, and retrieve all objects that are conformed to this protocol.
So I did something like :
func getObjectsToSynchronize() -> [Object]{
Array(realm.objects(Object.self)).filter({
if let $0 = $0 as? Synchronizable {
return true
}
return false
})
}
With Object the Realm Object type, but this type object by default doesn't implements my protocol, so I can't detect if the object is conform to the protocol Synchronizable, it says :
Expression pattern of type 'Object' cannot match values of type 'Synchronizable?'
Is there a way to do this ? I think I'm on the wrong way by querying in the Realm object.
Wrong way?
Maybe I have to create another Realm class object called SynchronizableObjectthat inherits from Object realm class.
This class will have a relationship to Realm objects that I want to be Synchronizable, such as :
class SynchronizableObject : Object {
// MARK: - Realm Relationships
dynamic var synchronizables : List<Object>()
}
And then I should query this class with the Realm object
#AnthonyR you can't query/filter directly RealmSwift.Object, you must inherit your model from RealmSwift.Object as you'v done
class Comment : Object, Synchronizable {
// ...
}
Then you can query/filter all objects of inherited type:
func getObjectsToSynchronize() -> Results<Comment> {
return realm.objects(Comment.self)
}
If you explain a little more what do you want to do may be I can help you
Related
I have been trying to abstract a little bit my Realm models, so I wanted to create a superclass model with a generic type. Then, create subclasses for the specific type.
I know Realm does not support storing a generic type. However, my question is:
Is it possible to store a specific defined subclass?
So the idea is to have a superclass:
class SuperClass<T: RealmCollectionValue> : Object {
#objc dynamic var pk: String = ""
let listProp = List<T>()
convenience init(pk: String){
self.init()
self.pk = pk
}
override static func primaryKey() -> String? {
return "pk"
}
}
Then implement a specific subclass:
class StringSubClass : SuperClass<String> {}
Is then the possibility to save in Realm instances of StringSubClass (as in fact, it is not a generic)?
From what I have found in this already answered question (which stands it is possible with an accepted answer): Store concrete generic subclass in Realm
You can specify the Realm to ignore the SuperClass by defining it to only handle the StringSubClass.
However, when trying it in Realm 3.13.1 with:
let realm = try! Realm(configuration: Realm.Configuration(objectTypes: [StringSubClass.self]))
try! realm.write {
realm.add(StringSubClass(pk: "mypk"))
}
The following exception is thrown when storing instances of StringSubClass
Terminating app due to uncaught exception 'RLMException', reason: 'Object type 'StringSubClass' is not managed by the Realm. If using a custom `objectClasses` / `objectTypes` array in your configuration, add `StringSubClass` to the list of `objectClasses` / `objectTypes`.'
I'm building a generic API for my Swift applications. I use CoreData for local storage and CloudKit for cloud synchronization.
in order to be able to work with my data objects in generic functions I have organized them as follows (brief summary):
Objects that go in the CoreData Database are NSManagedObject instances that conform to a protocol called ManagedObjectProtocol, which enables conversion to DataObject instances
NSManagedObjects that need to be cloud synced conform to a protocol called CloudObject which allows populating objects from records and vice-versa
Objects I use in the graphic layer of my apps are NSObject classes that conform to the DataObject protocol which allows for conversion to NSManagedObject instances
an object of a specific class. What I would like this code to look like is this:
for record in records {
let context = self.persistentContainer.newBackgroundContext()
//classForEntityName is a function in a custom extension that returns an NSManagedObject for the entityName provided.
//I assume here that recordType == entityName
if let managed = self.persistentContainer.classForEntityName(record!.recordType) {
if let cloud = managed as? CloudObject {
cloud.populateManagedObject(from: record!, in: context)
}
}
}
However, this gives me several errors:
Protocol 'CloudObject' can only be used as a generic constraint because it has Self or associated type requirements
Member 'populateManagedObject' cannot be used on value of protocol type 'CloudObject'; use a generic constraint instead
The CloudObject protocol looks as follows:
protocol CloudObject {
associatedtype CloudManagedObject: NSManagedObject, ManagedObjectProtocol
var recordID: CKRecordID? { get }
var recordType: String { get }
func populateManagedObject(from record: CKRecord, in context: NSManagedObjectContext) -> Promise<CloudManagedObject>
func populateCKRecord() -> CKRecord
}
Somehow I need to find a way that allows me to get the specific class conforming to CloudObject based on the recordType I receive. How would I Best go about this?
Any help would be much appreciated!
As the data formats of CoreData and CloudKit are not related you need a way to efficiently identify CoreData objects from a CloudKit record and vice versa.
My suggestion is to use the same name for CloudKit record type and CoreData entity and to use a custom record name (string) with format <Entity>.<identifer>. Entity is the record type / class name and identifier is a CoreData attribute with unique values. For example if there are two entities named Person and Event the record name is "Person.JohnDoe" or "Event.E71F87E3-E381-409E-9732-7E670D2DC11C". If there are CoreData relationships add more dot separated components to identify those
For convenience you could use a helper enum Entity to create the appropriate entity from a record
enum Entity : String {
case person = "Person"
case event = "Event"
init?(record : CKRecord) {
let components = record.recordID.recordName.components(separatedBy: ".")
self.init(rawValue: components.first!)
}
}
and an extension of CKRecord to create a record for specific record type from a Entity (in my example CloudManager is a singleton to manage the CloudKit stuff e.g. the zones)
extension CKRecord {
convenience init(entity : Entity) {
self.init(recordType: entity.rawValue, zoneID: CloudManager.shared.zoneID)
}
convenience init(entity : Entity, recordID : CKRecordID) {
self.init(recordType: entity.rawValue, recordID: recordID)
}
}
When you receive Cloud records extract the entity and the unique identifier. Then try to fetch the corresponding CoreData object. If the object exists update it, if not create a new one. On the other hand create a new record from a CoreData object with the unique record name. Your CloudObject protocol widely fits this pattern, the associated type is not needed (by the way deleting it gets rid of the error) but add a requirement recordName
var recordName : String { get set }
and an extension to get the recordID from the record name
extension CloudObject where Self : NSManagedObject {
var recordID : CKRecordID {
return CKRecordID(recordName: self.recordName, zoneID: CloudManager.shared.zoneID)
}
}
Swift is not Java, Swift is like C++, associatedType is a way of writing a generic protocol, and generics in Swift means C++ template.
In Java, ArrayList<String> is the same type as ArrayList<Integer>!!
In Swift (and C++) , Array<String> is NOT the same type as Array<Int>
So, you can't take an array of Arrays for example, you MUST make it an array of Array<SpecificType>
What did Apple do to make you able to make a "type-erased" array for example?
They made Array<T> extend Array<Any>.
If you want to immitate this in your code, how?
protocol CloudObject {
// Omitted the associatedtype (like you already done as in the replies)
//associatedtype CloudManagedObject: NSManagedObject, ManagedObjectProtocol
var recordID: CKRecordID? { get }
var recordType: String { get }
func populateManagedObject(from record: CKRecord, in context: NSManagedObjectContext) -> Promise<NSManagedObject & ManagedObjectProtocol>
func populateCKRecord() -> CKRecord
}
Then make the "generic protocol", this would be useful in safely and performance programming when the resolving of protocol is known at compile time
protocol CloudObjectGeneric: CloudObject {
// Generify it
associatedtype CloudManagedObject: NSManagedObject, ManagedObjectProtocol
// You don't need to redefine those, those are not changed in generic form
//var recordID: CKRecordID? { get }
//var recordType: String { get }
//func populateCKRecord() -> CKRecord
// You need a new function, which is the generic one
func populateManagedObject(from record: CKRecord, in context: NSManagedObjectContext) -> Promise<CloudObject>
}
Then make the generic protocol conform to the non-generic one, not to need writing 2 populateManagedObject functions in each implementation
extension CloudObjectGeneric {
// Function like this if the generic was a parameter, would be
// straightforward, just pass it with a cast to indicate you
// are NOT CALLING THE SAME FUNCTION, you are calling it from
// the generic one, but here the generic is in the return, so
// you will need a cast in the result.
func populateManagedObject(from record: CKRecord, in context: NSManagedObjectContext) -> Promise<CloudObject> {
let generic = populateManagedObject(from record: CKRecord, in context: NSManagedObjectContext)
return generic as! Promise<CloudObject> // In Promises I think this
// will NOT work, and you need .map({$0 as! CloudObject})
}
}
Consider the following, using Realm Swift:
class Shelf : Object {
let products = List<Product>()
}
and
class Product : Object {
let string: String = ""
let Shelves = LinkingObjects(fromType: Shelf.self, property: "products")
}
Now the question is, is it possible to perform a query like:
"What are all the shelves that match EXACTLY a specific product list?" (no more, no less).
I could not find a way to compare an array.
EDIT:
If I try doing this:
let results = realm.objects(Shelf.self).filter("%# == products",products)
I get the error:
Invalid predicate:
Key paths that include an array property must use aggregate operations
Thank you.
Each Realm model class inheriting from Object conforms to the Equatable protocol by default due to the fact that Object inherits from NSObject, which conforms to Equatable. If the elements of a List conform to the Equatable protocol, the List itself conforms to it as well.
Hence, you should be able to compare List<Product> instances by using the == function and you can also directly compare Shelf objects.
However, be aware that Realm overrides the == function, see Realm object's Equatable is implementation.
If you want a custom comparison, you can override the == function yourself.
Edit: I don't think this can be done using Realms filter method. However, if you don't mind getting an Array back as a result and not a Result collection, the below method can help you.
let searchedProducts = List([product1, product2, product3]) //these are Product instances
let results = Array(realm.objects(Shelf.self)).filter{
if $0.products.count != searchedProducts.count {
return false
}
for product in $0.products {
if searchedProducts.index(of: product) == nil {
return false
}
}
return true
}
The above code has been tested in Playground with a similar class and returned correct results.
I have a subclass of Object in Realm called BrowserCategory, and Artist, Decade and Genre are subclasses of BrowserCategory.
Right now each subclass of BrowserCategory has this LinkingObject property songs:
let songs = LinkingObjects(fromType: Song.self, property: "decade")
(for the Decade subclass, for example)
I'd like to write this in the BrowserCategory base class so I've tried this:
var songs = LinkingObjects(fromType: Song.self, property: className().lowercased())
However this returns the base class name and not the subclass name, giving the following error:
- Property 'Song.browsercategory' declared as origin of linking objects property 'Decade.songs' does not exist
Is there a way to do this the way I want to?
You are probably looking for type(of:self), which is polymorphic, as this demonstration illustrates:
class BrowserCategory {
func className() -> String {
return String(describing:type(of:self))
}
}
class Artist : BrowserCategory {}
class Decade : BrowserCategory {}
class Genre : BrowserCategory {}
let a = Artist()
a.className() // "Artist"
I should caution you, however, that to ask for a class's name as a string is a very odd thing to do. It is more usual to work with a class type as a type.
Ok, I have made this protocol to cover object caching with the help of Realm. In protocol I define cache: Object? which type is defined by Realm library.
protocol PersistantCaching {
var cache: Object? { get set }
}
Then I use this protocol in class ClientDetails it works.
class Client: PersistantCaching {
var cache: Object?
}
But Object is too general. So in my case I create Object subclass
class LocalClient: Object {
dynamic var name = ""
}
And now if I change class Client to support LocalClient like this
class Client: PersistantCaching {
var cache: LocalClient?
}
I get an error, that Type 'Client' does not conform to protocol 'PersistantCaching'
How to write generic protocol that define a variable which also accepts subclass of specified Type?
Use an associatedtype:
protocol PersistantCaching {
associatedtype CacheObject: Object
var cache: CacheObject? { get set }
}
(I'm assuming here that you want the cache always to be a subclass of Object.)