How to add Values to NSObject Model Variables in Swift? - ios

I have created separate NSObject class called ProfileModel
like below:
class ProfileModel : NSObject, NSCoding{
var userId : String!
var phone : String!
var firstName : String!
var email : String!
var profileImageUrl : String!
var userAddresses : [ProfileModelUserAddress]!
// Instantiate the instance using the passed dictionary values to set the properties values
init(fromDictionary dictionary: [String:Any]){
userId = dictionary["userId"] as? String
phone = dictionary["phone"] as? String
firstName = dictionary["firstName"] as? String
email = dictionary["email"] as? String
profileImageUrl = dictionary["profileImageUrl"] as? String
}
/**
* Returns all the available property values in the form of [String:Any] object where the key is the approperiate json key and the value is the value of the corresponding property
*/
func toDictionary() -> [String:Any]
{
var dictionary = [String:Any]()
if userId != nil{
dictionary["userId"] = userId
}
if phone != nil{
dictionary["phone"] = phone
}
if firstName != nil{
dictionary["firstName"] = firstName
}
if email != nil{
dictionary["email"] = email
}
if profileImageUrl != nil{
dictionary["profileImageUrl"] = profileImageUrl
}
return dictionary
}
/**
* NSCoding required initializer.
* Fills the data from the passed decoder
*/
#objc required init(coder aDecoder: NSCoder)
{
userId = aDecoder.decodeObject(forKey: "userId") as? String
userType = aDecoder.decodeObject(forKey: "userType") as? String
phone = aDecoder.decodeObject(forKey: "phone") as? String
firstName = aDecoder.decodeObject(forKey: "firstName") as? String
email = aDecoder.decodeObject(forKey: "email") as? String
profileImageUrl = aDecoder.decodeObject(forKey: "profileImageUrl") as? String
}
/**
* NSCoding required method.
* Encodes mode properties into the decoder
*/
#objc func encode(with aCoder: NSCoder)
{
if userId != nil{
aCoder.encode(userId, forKey: "userId")
}
if phone != nil{
aCoder.encode(phone, forKey: "phone")
}
if firstName != nil{
aCoder.encode(firstName, forKey: "firstName")
}
if email != nil{
aCoder.encode(email, forKey: "email")
}
if profileImageUrl != nil{
aCoder.encode(profileImageUrl, forKey: "profileImageUrl")
}
}
}
In RegistrationViewController I adding firstName value which i need to show in ProfileViewController How ?
In RegistrationViewController i am adding firstName and phone values which i need in ProfileViewController:
class RegistrationViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var firstNameTextField: FloatingTextField!
var userModel : ProfileModel?
override func viewDidLoad() {
let userID: String=jsonObj?["userId"] as? String ?? ""
self.userModel?.firstName = self.firstNameTextField.text
self.userModel?.phone = phoneTextField.text
}
}
This is ProfileViewController here in name and number i am not getting firstName and phone values why?:
class ProfileViewController: UIViewController {
#IBOutlet var name: UILabel!
#IBOutlet var number: UILabel!
var userModel : ProfileModel?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
name.text = userModel?.firstName
number.text = userModel?.phone
}
}
PLease help me with code.

You cannot set firstName or phone to the userModal which is nil. First you should create an instance, and then you can pass it through your controllers. We should change code step by step:
class ProfileModel {
var userId : String?
var phone : String?
var firstName : String?
var email : String?
var profileImageUrl : String?
var userAddresses : [ProfileModelUserAddress]?
init() {}
}
Second, you need to reach ProfileModel instance from both of your ViewController classes. For this, you can create a singleton class:
class ProfileManager {
static var shared = ProfileManager()
var userModel: ProfileModel?
private init() {}
}
Then you can reach it from both of your ViewControllers:
class RegistrationViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var firstNameTextField: FloatingTextField!
override func viewDidLoad() {
super.viewDidLoad()
let userModel = ProfileModel()
userModel.firstName = self.firstNameTextField.text
ProfileManager.shared.userModel = userModel
}
}
Other VC:
class ProfileViewController: UIViewController {
#IBOutlet var name: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
if let userModel = ProfileManager.shared.userModel,
let firstName = userModel.firstName {
name.text = firstName
}
}
}
Modify it as you wanted.

Related

How to initialize multiple dictionary in json in 1 NSObject using SwiftyJson

My API response is look like this
{
"error": false,
"id": "6",
"user_id": 7,
"users": [
{
"user_id": 1,
"username": "spiderman"
},
{
"user_id": 7,
"username": "wonderwoman"
}
],
"info": [
{
"id": 471,
"message": "abc",
"age": 10,
}
]
}
I know how to initialize the value of id,user_id and error in NSOject. But I dont know how can I initialize the array of users and info in the same NSObject class.
Now I initialize the JSON like this
import UIKit
import SwiftyJSON
class MyItem: NSObject {
var userId : Int
var error : Bool
var id : Int
init?(dict: [String :JSON]) {
self.id = dict["id"]?.int ?? 0
self.error = dict["error"]?.bool ?? false
self.userId = dict["userId"]?.int ?? 0
}
}
Now the problem is I don't know how to initialize data inside the users and info dictionary.How should I arrange it and how can I use it in other class
Kindly give an example.
Use as below,
Root Class :-
import Foundation
import SwiftyJSON
class RootClass : NSObject, NSCoding{
var error : Bool!
var id : String!
var info : [Info]!
var userId : Int!
var users : [User]!
/**
* Instantiate the instance using the passed json values to set the properties values
*/
init(fromJson json: JSON!){
if json.isEmpty{
return
}
error = json["error"].boolValue
id = json["id"].stringValue
info = [Info]()
let infoArray = json["info"].arrayValue
for infoJson in infoArray{
let value = Info(fromJson: infoJson)
info.append(value)
}
userId = json["user_id"].intValue
users = [User]()
let usersArray = json["users"].arrayValue
for usersJson in usersArray{
let value = User(fromJson: usersJson)
users.append(value)
}
}
/**
* Returns all the available property values in the form of [String:Any] object where the key is the approperiate json key and the value is the value of the corresponding property
*/
func toDictionary() -> [String:Any]
{
let dictionary = [String:Any]()
if error != nil{
dictionary["error"] = error
}
if id != nil{
dictionary["id"] = id
}
if info != nil{
var dictionaryElements = [[String:Any]]()
for infoElement in info {
dictionaryElements.append(infoElement.toDictionary())
}
dictionary["info"] = dictionaryElements
}
if userId != nil{
dictionary["user_id"] = userId
}
if users != nil{
var dictionaryElements = [[String:Any]]()
for usersElement in users {
dictionaryElements.append(usersElement.toDictionary())
}
dictionary["users"] = dictionaryElements
}
return dictionary
}
/**
* NSCoding required initializer.
* Fills the data from the passed decoder
*/
#objc required init(coder aDecoder: NSCoder)
{
error = aDecoder.decodeObject(forKey: "error") as? Bool
id = aDecoder.decodeObject(forKey: "id") as? String
info = aDecoder.decodeObject(forKey: "info") as? [Info]
userId = aDecoder.decodeObject(forKey: "user_id") as? Int
users = aDecoder.decodeObject(forKey: "users") as? [User]
}
/**
* NSCoding required method.
* Encodes mode properties into the decoder
*/
func encode(with aCoder: NSCoder)
{
if error != nil{
aCoder.encode(error, forKey: "error")
}
if id != nil{
aCoder.encode(id, forKey: "id")
}
if info != nil{
aCoder.encode(info, forKey: "info")
}
if userId != nil{
aCoder.encode(userId, forKey: "user_id")
}
if users != nil{
aCoder.encode(users, forKey: "users")
}
}
}
User Class :-
import Foundation
import SwiftyJSON
class User : NSObject, NSCoding{
var userId : Int!
var username : String!
/**
* Instantiate the instance using the passed json values to set the properties values
*/
init(fromJson json: JSON!){
if json.isEmpty{
return
}
userId = json["user_id"].intValue
username = json["username"].stringValue
}
/**
* Returns all the available property values in the form of [String:Any] object where the key is the approperiate json key and the value is the value of the corresponding property
*/
func toDictionary() -> [String:Any]
{
let dictionary = [String:Any]()
if userId != nil{
dictionary["user_id"] = userId
}
if username != nil{
dictionary["username"] = username
}
return dictionary
}
/**
* NSCoding required initializer.
* Fills the data from the passed decoder
*/
#objc required init(coder aDecoder: NSCoder)
{
userId = aDecoder.decodeObject(forKey: "user_id") as? Int
username = aDecoder.decodeObject(forKey: "username") as? String
}
/**
* NSCoding required method.
* Encodes mode properties into the decoder
*/
func encode(with aCoder: NSCoder)
{
if userId != nil{
aCoder.encode(userId, forKey: "user_id")
}
if username != nil{
aCoder.encode(username, forKey: "username")
}
}
}
Info Class :-
import Foundation
import SwiftyJSON
class Info : NSObject, NSCoding{
var age : Int!
var id : Int!
var message : String!
/**
* Instantiate the instance using the passed json values to set the properties values
*/
init(fromJson json: JSON!){
if json.isEmpty{
return
}
age = json["age"].intValue
id = json["id"].intValue
message = json["message"].stringValue
}
/**
* Returns all the available property values in the form of [String:Any] object where the key is the approperiate json key and the value is the value of the corresponding property
*/
func toDictionary() -> [String:Any]
{
let dictionary = [String:Any]()
if age != nil{
dictionary["age"] = age
}
if id != nil{
dictionary["id"] = id
}
if message != nil{
dictionary["message"] = message
}
return dictionary
}
/**
* NSCoding required initializer.
* Fills the data from the passed decoder
*/
#objc required init(coder aDecoder: NSCoder)
{
age = aDecoder.decodeObject(forKey: "age") as? Int
id = aDecoder.decodeObject(forKey: "id") as? Int
message = aDecoder.decodeObject(forKey: "message") as? String
}
/**
* NSCoding required method.
* Encodes mode properties into the decoder
*/
func encode(with aCoder: NSCoder)
{
if age != nil{
aCoder.encode(age, forKey: "age")
}
if id != nil{
aCoder.encode(id, forKey: "id")
}
if message != nil{
aCoder.encode(message, forKey: "message")
}
}
}
The best way to do this is to create 2 different classes for user and info as follows:
class MyItem : NSObject {
var error : Bool!
var id : String!
var info : [Info]!
var userId : Int!
var users : [User]!
init(fromJson json: JSON!){
if json == nil{
return
}
error = json["error"].boolValue
id = json["id"].stringValue
info = [Info]()
let infoArray = json["info"].arrayValue
for infoJson in infoArray{
let value = Info(fromJson: infoJson)
info.append(value)
}
userId = json["user_id"].intValue
users = [User]()
let usersArray = json["users"].arrayValue
for usersJson in usersArray{
let value = User(fromJson: usersJson)
users.append(value)
}
}
}
class User : NSObject {
var userId : Int!
var username : String!
init(fromJson json: JSON!){
if json == nil{
return
}
userId = json["user_id"].intValue
username = json["username"].stringValue
}
}
class Info : NSObject {
var age : Int!
var id : Int!
var message : String!
init(fromJson json: JSON!){
if json == nil{
return
}
age = json["age"].intValue
id = json["id"].intValue
message = json["message"].stringValue
}
}
By doing this you would be able to directly access the value of user and info like for eg: MyItem.users[index].userId
Do Like this,
class MyItem: NSObject {
var userId : Int
var error : Bool
var id : Int
var users : [[String:Any]] = []
var info : [[String:Any]] = []
init?(dict: [String :JSON]) {
self.id = dict["id"]?.int ?? 0
self.error = dict["error"]?.bool ?? false
self.userId = dict["userId"]?.int ?? 0
self.users = dict["users"] ?? []
self.info = dict["info"] ?? []
}
}
No offense to the developers of SwiftyJSON, it is a great library, but in Swift 4 to decode JSON SwiftyJSON became obsolete.
With the Decodable protocol you are able to decode the JSON without any extra code.
Create one struct including the two substructs, the coding keys are only necessary to map snake_case to camelCase.
struct MyItem: Decodable {
private enum CodingKeys: String, CodingKey { case userId = "user_id", error, id, users, info}
let userId : Int
let error : Bool
let id : String
let users : [User]
let info : [Info]
struct User : Decodable {
private enum CodingKeys: String, CodingKey { case userId = "user_id", username}
let userId : Int
let username : String
}
struct Info : Decodable {
let message : String
let id, age : Int
}
}
Now decode the JSON
let jsonString = """
{
"error": false,
"id": "6",
"user_id": 7,
"users": [{"user_id": 1, "username": "spiderman"},{"user_id": 7,"username": "wonderwoman"}],
"info": [{"id": 471,"message": "abc", "age": 10}]
}
"""
do {
let data = Data(jsonString.utf8)
let decoder = JSONDecoder()
let result = try JSONDecoder().decode(MyItem.self, from: data)
for user in result.users {
print(user.userId, user.username)
}
} catch { print(error) }

How do I get Firebase database value into UILabel text?

I'm trying to read a value from my Firebase database. I then want to change UILabel text to the database child value. Seems pretty simple, but I cannot figure out why the value is reading blank.
Here is my Firebase JSON:
{
"pilots" : {
"HpPzn0XUqMgsKhUOpH75lHIhyFA3" : {
"pilot" : "First Lastname",
"weight" : 180
}
}
}
Here are the Firebase rules, just for testing at the moment:
{
"rules": {
"pilots": {
".read": true,
".write": true
}
}
}
Finally the Swift 3 code, which is probably ugly as sin. First app after reading and online lessons.
import UIKit
import Firebase
import FirebaseCore
import FirebaseAuth
import FirebaseDatabase
class MainMenuViewController: UIViewController {
#IBOutlet weak var pilotUsername: UILabel!
#IBOutlet weak var dateTime: UILabel!
#IBOutlet weak var aircraftLabel: UILabel!
#IBOutlet weak var riskScoreInt: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let ref = FIRDatabase.database().reference()
let userID = FIRAuth.auth()?.currentUser?.uid
ref.child("pilots").child(userID!).child("pilot").observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
let username = value?["username"] as? String ?? ""
self.pilotUsername.text = username
print(username)
// ...
}) { (error) in
print(error.localizedDescription)
}
}
}
I'm just using the example code from the Firebase documentation. There's a line of code (in the example) after
let username = value?["username"] as? String ?? ""
that is :
let user = User.init(username: username)
but it gives me an error. "Use of unresolved identifier 'User'"
I don't think I need that line of code, since nothing like it is used in the examples and lessons that I've folowed.
Thank's in advance. This is my first time posting to Stack Overflow.
import FirebaseDatabase
class User {
// MARK: Properties
var firstname: String
var lastname: String
var username: String { return "\(firstname)\(lastname)" }
// MARK: Initializers
init(firstname: String, lastname: String) {
self.firstname = firstname
self.lastname = lastname
}
init?(snapshot: FIRDataSnapshot) {
guard
let firstname = snapshot.childSnapshot(forPath: "First").value as? String,
let lastname = snapshot.childSnapshot(forPath: "Lastname").value as? String
else { return nil }
self.firstname = firstname
self.lastname = lastname
}
}
Then
ref.child("pilots").child(userID!).child("pilot").observeSingleEvent(of: .value, with: { [weak self] (snapshot) in
if let user = User(snapshot: snapshot) {
self?.pilotUsername.text = user.username
}
}) { (error) in
print(error.localizedDescription)
}

NSCoding custom object child array not persisting

I have two classes : Contact and Bill. Contact has an array of type Bill.
When I persist using NSKeyedArchiver my contacts persist just fine, however, it does not persist the Bill array.
Each time I add a a Bill or a Contact I call the insertNewObject() method in persist.
Here are my classes :
/* Persist.swift */
import Foundation
class Persist {
static let sharedInstance = Persist()
let delegate = UIApplication.sharedApplication().delegate as! AppDelegate
var contactsFilePath : String {
let manager = NSFileManager.defaultManager()
let url = manager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first! as NSURL
return url.URLByAppendingPathComponent("\(delegate.userId):objectsArrayz").path!
}
func insertNewObject(){
NSKeyedArchiver.archiveRootObject(delegate.contacts!, toFile: contactsFilePath)
}
func retrieveContracts(){
if let array = NSKeyedUnarchiver.unarchiveObjectWithFile(contactsFilePath) as? [Contact] {
delegate.contacts = array
}
}
func deleteContact(rowNum : Int){
delegate.contacts!.removeAtIndex(rowNum)
NSKeyedArchiver.archiveRootObject(delegate.contacts!, toFile: contactsFilePath)
}
/* Contact.swift */
import Foundation
class Contact : NSObject, NSCoding{
var image : UIImage?
var firstName : String?
var lastName : String?
var email : String?
var phoneNumber : String?
var address : String?
var bills : [Bill]?
init(image: UIImage, firstName : String, lastName : String, email : String, phoneNumber : String, address : String, bills : [Bill]) {
self.image = image
self.firstName = firstName
self.lastName = lastName
self.email = email
self.phoneNumber = phoneNumber
self.address = address
self.bills = bills
}
// MARK: NSCoding
required convenience init?(coder decoder: NSCoder) {
guard let image = decoder.decodeObjectForKey("image") as? UIImage,
let firstName = decoder.decodeObjectForKey("firstName") as? String,
let lastName = decoder.decodeObjectForKey("lastName") as? String,
let email = decoder.decodeObjectForKey("email") as? String,
let phoneNumber = decoder.decodeObjectForKey("phoneNumber") as? String,
let address = decoder.decodeObjectForKey("address") as? String,
let bills = decoder.decodeObjectForKey("bills") as? [Bill]
else {
return nil
}
self.init(
image: image,
firstName: firstName,
lastName : lastName,
email : email,
phoneNumber : phoneNumber,
address : address,
bills : bills
)
}
func encodeWithCoder(coder: NSCoder) {
coder.encodeObject(self.image, forKey: "image")
coder.encodeObject(self.firstName, forKey: "firstName")
coder.encodeObject(self.lastName, forKey: "lastName")
coder.encodeObject(self.email, forKey: "email")
coder.encodeObject(self.phoneNumber, forKey: "phoneNumber")
coder.encodeObject(self.address, forKey: "address")
coder.encodeObject(self.bills, forKey: "bills")
}
}
/* Bill.swift*/
import Foundation
class Bill : NSObject, NSCoding{
var service : String?
var subtotal : Double?
var taxes : Double?
var total : Double?
init(service : String, subtotal : Double, taxes : Double, total: Double) {
self.service = service
self.subtotal = subtotal
self.taxes = taxes
}
// MARK: NSCoding
required convenience init?(coder decoder: NSCoder) {
guard let service = decoder.decodeObjectForKey("service") as? String,
let subtotal = decoder.decodeObjectForKey("subtotal") as? Double,
let taxes = decoder.decodeObjectForKey("taxes") as? Double,
let total = decoder.decodeObjectForKey("total") as? Double
else {
return nil
}
self.init(
service: service,
subtotal: subtotal,
taxes: taxes,
total: total
)
}
func encodeWithCoder(coder: NSCoder) {
coder.encodeObject(self.service, forKey: "service")
coder.encodeObject(self.subtotal, forKey: "subtotal")
coder.encodeObject(self.taxes, forKey: "taxes")
coder.encodeObject(self.total, forKey: "total")
}
}
Here is a guide from the apple dev docs (in objective-c):
Discussion You must return self from initWithCoder:. If you have an
advanced need that requires substituting a different object after
decoding, you can do so in awakeAfterUsingCoder:
https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Archiving/Articles/codingobjects.html
- (void)encodeWithCoder:(NSCoder *)coder {
[super encodeWithCoder:coder];
// Implementation continues
}
- (id)initWithCoder:(NSCoder *)coder {
self = [super init];
if (self) {
_firstName = [coder decodeObjectForKey:ASCPersonFirstName];
_lastName = [coder decodeObjectForKey:ASCPersonLastName];
_height = [coder decodeFloatForKey:ASCPersonHeight];
}
return self;
}
A call to super.init() is required in the serializable class's init method.
Snippet from Bill.swift
required init?(coder decoder: NSCoder) {
super.init()
service = decoder.decodeObjectForKey("service") as? String
subtotal = decoder.decodeObjectForKey("subtotal") as? Double
taxes = decoder.decodeObjectForKey("taxes") as? Double
total = decoder.decodeObjectForKey("total") as? Double
services = decoder.decodeObjectForKey("services") as? [Service]
}

How to save any class in NSUserDefaults [duplicate]

This question already has answers here:
Saving array using NSUserDefaults crashes app
(1 answer)
How to store custom objects in NSUserDefaults
(7 answers)
Closed 7 years ago.
I tried several different method that I can to save this class in NSUserDefaults. I don't know how to save class with override function. How can I make it?
class CountryEntity: AnyObject {
private(set) var id: UInt = 0
private(set) var name = ""
override func cityData(data: Dictionary<String, AnyObject>!) {
id = data.uint(key: "id")
name = data.string(key: "name")
}
}
I tried like that but it doesn't help me
private static var _selectedCountryEntity: AnyObject? = NSUserDefaults.standardUserDefaults().objectForKey(countryNameKey) {
didSet {
let savedData = NSKeyedArchiver.archivedDataWithRootObject(selectedCountryEntity as! NSData)
NSUserDefaults.standardUserDefaults().setObject(savedData, forKey: countryNameKey)
NSUserDefaults.standardUserDefaults().synchronize()
}
}
static var selectedCountryEntity: AnyObject? {
get {
return _selectedCountryEntity
}
set {
// if newValue != _selectedCountryTuple {
_selectedCountryEntity = newValue
// }
}
}
To store custom classes in NSUserDefaults, the data type needs to be a subclass of NSObject and should adhere to NSCoding protocol.
1) Create a custom class for your data
class CustomData: NSObject, NSCoding {
let name : String
let url : String
let desc : String
init(tuple : (String,String,String)){
self.name = tuple.0
self.url = tuple.1
self.desc = tuple.2
}
func getName() -> String {
return name
}
func getURL() -> String{
return url
}
func getDescription() -> String {
return desc
}
func getTuple() -> (String,String,String) {
return (self.name,self.url,self.desc)
}
required init(coder aDecoder: NSCoder) {
self.name = aDecoder.decodeObjectForKey("name") as! String
self.url = aDecoder.decodeObjectForKey("url") as! String
self.desc = aDecoder.decodeObjectForKey("desc") as! String
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(self.name, forKey: "name")
aCoder.encodeObject(self.url, forKey: "url")
aCoder.encodeObject(self.desc, forKey: "desc")
}
}
2) To save data use following function:
func saveData()
{
let data = NSKeyedArchiver.archivedDataWithRootObject(custom)
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(data, forKey:"customArray" )
}
3) To retrieve:
if let data = NSUserDefaults().dataForKey("customArray"),
custom = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? [CustomData] {
// Do something with retrieved data
for item in custom {
print(item)
}
}
Note: Here I am saving and retrieving an array of trhe custom class objects.

Swift NSObject subclass get BAD_ACCESS

I try to persiste my object with NSCoding but i always get BAD_ACCESS ERROR To avoid multi multiple like variable, class, i put all common variable in RObject. I think i do something wrong the the init but i don't know what.
the error was thow in this function
func parseInfo(allInfos : String) -> Void {
if let all : JSON = JSON.parse(allInfos) as JSON? {
if let info = all.asArray
{
for description in info
{
var track : RInfo = SCTracks(js: description)
self.arrayTracks.addObject(track)
} // Therad 1: EXC_BAD_ACCESS(code=2, address=0x27...)
}
}
}
The Log doesn't show any thing
My Common Class
class RObject : NSObject, NSCoding {
var id : Int? = 0
var kind : String?
override init() { super.init() }
init(js :JSON) {
self.kind = js["kind"].asString
self.id = js["id"].asInt
super.init()
}
required
init(coder aDecoder: NSCoder) {
self.id = aDecoder.decodeIntegerForKey("id") as Int
self.kind = aDecoder.decodeObjectForKey("kind") as? String
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeInteger(self.id!, forKey: "id")
aCoder.encodeObject(self.kind, forKey: "kind")
}
}
My class Rinfo who inherits from RObject
class RInfo : RObject {
var title :String?
var uri :String?
var license :String?
var release :String?
var user :RUser!
override init() { super.init() }
required init(coder: NSCoder) {
self.title = coder.decodeObjectForKey("title") as? String
self.user = coder.decodeObjectForKey("user") as RUser
self.license = coder.decodeObjectForKey("license") as? String
self.uri = coder.decodeObjectForKey("uri") as? String
self.release = coder.decodeObjectForKey("release") as? String
super.init(coder: coder)
}
init(js :JSON) {
self.user = js(js: js["user"])
self.title = js["title"].asString
self.license = js["license"].asString
self.uri = js["uri"].asString
self.release = js["release"].asString
super.init(js: js)
}
override func encodeWithCoder(encoder: NSCoder) {
encoder.encodeObject(self.title, forKey: "title")
encoder.encodeObject(self.user, forKey: "user")
encoder.encodeObject(self.uri, forKey: "uri")
encoder.encodeObject(self.license, forKey: "license")
}
}
Thanks for any help !
I Solve my problem by remove variable release in RInfo. that strange

Resources