Store integers in base data with Swift and Xcode

While Strings looks fine, I'm having trouble storing integers in Core Data. After learning and reading the available information, it does not seem to help me who does not have an Objective-C background. (Swift seemed like a direct language, like the languages ​​that I fluent in PHP / OOPHP / JavaScript / VBScript / ... so I started playing with it and still could do whatever I wanted, almost)

Now I want to get the JSON data and save it in Core Data p>

Here is my basic data

Entity name: Category 

Its attributes:

 id Int16 title String description String 

My Swift Model? file: Category.swift

 import CoreData class Category: NSManagedObject { @NSManaged var id: Int //should I declare this as Int16? @NSManaged var title: String @NSManaged var description: String } 

Am I using the SwiftyJASON extension? and the NSURLSession protocol? to get the data and analyze it as follows:

 import UIKit import CoreData class ViewController: UIViewController { let managedObjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext override func viewDidLoad() { super.viewDidLoad() fetchData() } func fetchData() { var url = NSURL.URLWithString("http://domain.com/index.php?r=appsync/read&id=category") var session = NSURLSession.sharedSession() session.dataTaskWithURL(url, completionHandler: {(data, response, error) in // parse data into json let json = JSONValue(data) let entityDescription = NSEntityDescription.entityForName("Category", inManagedObjectContext: self.managedObjectContext) let category = Category(entity: entityDescription, insertIntoManagedObjectContext: self.managedObjectContext) for item in json.array! { category.id = item["id"].string!.toInt()! //goes KABOOM! category.title = item["title"].string! category.description = item["description"].string! managedObjectContext?.save(nil) } dispatch_async(dispatch_get_main_queue()) { // do something } }).resume() } } 

Suppose the JASON data is:

 [{"id":"1","title":"cat1","description":"blabala one"},{"id":"2","title":"cat2","description":"blabala two"}] 

In the line where category.id = item["id"].string!.toInt()! xcode goes KABOOM, what am I doing wrong here?

Notes / Additional Questions:

  • I tried changing the identifier type inside Core Data to Int32 and then declaring it as the only Int in the model (not Int16 or Int32), which reduced some errors, but xCode still crashes

  • Probably the way I am looping is not the best way to do this, which is the best way to store the data array in the main data at once?

  • In most tutorials, I did not see an identifier for entities (tables), did I miss something here?

Literature:

EDIT> Working code:

Category.swift model file, which can be generated automatically with File> New> File> iOS> Core Data> Subclass NSManagedObject [swift, no need to bind the header, but you need to manually add the @objc line as shown below)

 import CoreData @objc(Category) //Wouldn't work without this class Category: NSManagedObject { @NSManaged var id: NSNumber //has to be NSNumber @NSManaged var title: String @NSManaged var mydescription: String //"description" is reserved so is "class" } 

ViewController.swift

 import UIKit import CoreData class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() fetchData() } func fetchData() { var url = NSURL.URLWithString("http://domain.com/index.php?r=appsync/read&id=category") var session = NSURLSession.sharedSession() session.dataTaskWithURL(url, completionHandler: {(data, response, error) in let json = JSONValue(data) let managedObjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext //this line had to be moved here let entityDescription = NSEntityDescription.entityForName("Category", inManagedObjectContext: managedObjectContext) for item in json.array! { let category = Category(entity: entityDescription, insertIntoManagedObjectContext: managedObjectContext) //this line has to be in inside for loop category.id = item["id"].string!.toInt()! category.title = item["title"].string! category.mydescription = item["description"].string! managedObjectContext?.save(nil) } dispatch_async(dispatch_get_main_queue()) { // do something } }).resume() } } 

Example of fetching a data code:

 func requestData() { let appDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate let context:NSManagedObjectContext = appDel.managedObjectContext! var request = NSFetchRequest(entityName: "Category") request.returnsObjectsAsFaults = false var results:NSArray = context.executeFetchRequest(request, error: nil) //println(results) for category in results { var cat = category as Category println("\(cat.id),\(cat.title),\(cat.mydescription)") } } 

PS Be sure to clean the project and remove the application from the simulator after changing the model

+7
swift xcode6 core-data
source share
2 answers

Scalar types (integers, float, boolean) in the kernel data are split into the current Swift blind (5). Use NSNumber for properties and feed the radar.

 object.intProperty = NSNumber(int:Int(item["id"] as String)) 

(printed by phone, sorry if this is wrong, and I know that this is disgusting code - hence the radar file!)

Or, in your particular case, looking at JSON, use String. In any case, these identifiers appear on strings.

+6
source share

Updated for Swift 2

If your JSON data is indeed of type [[String:String]] , you can use the following code to set category.id :

 if let unwrappedString = item["id"], unwrappedInt = Int(unwrappedString) { category.id = unwrappedInt } 
+1
source share

All Articles