Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Realm Swift Init

Tags:

swift

realm

I am trying to use the init for Realm in Swift. I have tried the following

override init(value: AnyObject) { 
    super.init() 
    println("this is not called") 
} 

required init() { 
    super.init() 
    println("this is called") 
}

I want to be able to pass an object into the initializer, however, I can't get the first function to be called.

like image 219
leech Avatar asked Jun 26 '15 23:06

leech


People also ask

What is realm for Swift?

Realm Swift is an easy to use alternative to SQLite and Core Data that makes persisting, querying, and syncing data as simple as working directly with native Swift objects. Deploy a sample appView documentation.

How do we create a realm object?

Create an Object with a Map Property Set keys and values on the object and then add the object to the realm. Set the object's keys and values directly inside a write transaction. Use key-value coding to set or update keys and values inside a write transaction.

How do I close a realm in Swift?

There is no need to manually close a realm in Swift or Objective-C.


1 Answers

My solution in Swift 3

Custom initializer:

class Branches: Object {

    dynamic var key: String = NSUUID().uuidString
    dynamic var formattedAddress: String = ""
    dynamic var latitude: Double = 0.0
    dynamic var longitude: Double = 0.0


 convenience init(formattedAddress: String, latitude: Double, longitude: Double) {
    self.init()
    self.formattedAddress = formattedAddress
    self.latitude = latitude
    self.longitude = longitude
 }

 override static func primaryKey() -> String? {
    return "key"
  }
}
like image 144
Zhanserik Avatar answered Sep 21 '22 23:09

Zhanserik