SwiftyJSONRealmObject 1.0.0

SwiftyJSONRealmObject 1.0.0

TestsTested
LangLanguage SwiftSwift
License MIT
ReleasedLast Release Mar 2017
SwiftSwift Version 3.0
SPMSupports SPM

Maintained by Alex Corlatti.



 
Depends on:
RealmSwift>= 0
SwiftyJSON>= 0
 

  • By
  • Alex Corlatti

SwiftyJSONRealmObject

Example

To run the example project, clone the repo, and run pod install from the Example directory first.

Requirements

  • iOS 8.0+ / Mac OS X 10.9+ / tvOS 9.0+ / watchOS 2.0+
  • Xcode 7.3+

Usage

Your Realm object can hinerit from SwiftyJSONRealmObject, than means that you have to implement the required initializer convenience required init(json: JSON) that maps the JSON value with your object properties like in this way

class MyObject: SwiftyJSONRealmObject {

    dynamic var id = ""
    dynamic var type = ""
    dynamic var name = ""

    override static func primaryKey() -> String? {

        return "id"

    }

    convenience required init(json: JSON) {

        self.init()

        self.id = json["id"].stringValue
        self.type = json["type"].stringValue
        self.name = json["name"].stringValue

    }

}

Now you can create your object directly from JSON

...

let json = [
   "id": "1",
   "type": "type1",
    "name": "Single Object"
]

let myObj = MyObject(json: JSON(json))

// Do something with it and/or save it in Realm

...

You can also create list of object with SwiftyJSONRealmObject class method createList(ofType type: T.Type, fromJson json: JSON)

...

let jsonList = [

    [ "id": "1", "type": "type1", "name": "Object 1" ],
    [ "id": "2", "type": "type2", "name": "Object 2" ],
    [ "id": "3", "type": "type3", "name": "Object 3" ]

]

let myObjList = SwiftyJSONRealmObject.createList(ofType: MyObject.self, fromJson: JSON(jsonList))

// Do something with it and/or save it in Realm

...

Use it with AlamofireRouter and AlamofireUIManager

SwiftyJSONRealmObject is perfect to itegrate in your Web API manger suite composed by AlamofireRouter and AlamofireUIManager. (See the specific documentation to understand how they works)

...
let netManager = AlamofireUIManager.sharedInstance

netManager.request(MyAPI.myRequest(myParameter: "aValue"), completionHandler: { json in

    let myObj = MyObject(json: json)

    // Do some stuff

})
...

Author

Alex Corlatti, [email protected]

License

SwiftyJSONRealmObject is available under the MIT license. See the LICENSE file for more info.