Codigo de Ejemplo numero 1:
//
// ViewController.swift
// BookStore
//JEHOVANI DE JESUS CHAVEZ SEGOVIA 2561842011
import UIKit
import CoreData
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var managedObjectContext: NSManagedObjectContext!;
@IBOutlet weak var myTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
managedObjectContext = appDelegate.managedObjectContext! as NSManagedObjectContext
//myTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
//myTableView.dataSource = self
//myTableView.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
println(loadBooks().count)
return loadBooks().count
//return 5
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! UITableViewCell
var book: Book = loadBooks()[indexPath.row] as! Book
cell.textLabel!.text = book.title
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
}
func loadBooks() -> Array {
var error: NSError? = nil
var fetchRequest = NSFetchRequest(entityName: "Book")
let result : [AnyObject] = managedObjectContext!.executeFetchRequest(fetchRequest, error:&error)!
return result;
}
@IBAction func addNew(sender: AnyObject) {
let entity = NSEntityDescription.entityForName("Book", inManagedObjectContext:managedObjectContext)
var book = Book(entity: entity!,insertIntoManagedObjectContext:managedObjectContext)
book.title = "My Book:" + String(loadBooks().count)
var error: NSError?
managedObjectContext.save(&error)
myTableView.reloadData()
}
}
CLASES
//
// Author.swift
// BookStore
//
import Foundation
import CoreData
class Author: NSManagedObject {
@NSManaged var firstName: String
@NSManaged var lastName: String
@NSManaged var books: Book
}
//
// Book.swift
// BookStore
import Foundation
import CoreData
class Book: NSManagedObject {
@NSManaged var title: String
@NSManaged var price: NSNumber
@NSManaged var yearPublished: NSNumber
@NSManaged var author: Author
}