Last active
March 31, 2019 06:41
-
-
Save donguri9/75e91177317359c59fec59e8e41d95ff to your computer and use it in GitHub Desktop.
CoreDataで作るTableView
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import CoreData | |
class ViewController: UIViewController,UITextFieldDelegate { | |
@IBOutlet weak var textField: UITextField! | |
@IBOutlet weak var tableView: UITableView! | |
var monsters:[Monster] = [] | |
var manager = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
textField.delegate = self | |
let getData = NSFetchRequest<NSFetchRequestResult>(entityName: "Monster") | |
do{ | |
monsters = try manager.fetch(getData) as! [Monster] | |
}catch{ | |
print("エラーだよ") | |
} | |
} | |
func textFieldShouldReturn(_ textField: UITextField) -> Bool { | |
textField.resignFirstResponder() | |
let newObj = Monster(context: self.manager) | |
newObj.name = textField.text | |
self.monsters.append(newObj) | |
(UIApplication.shared.delegate as! AppDelegate).saveContext() | |
tableView.reloadData() | |
textField.text = "" | |
return true | |
} | |
} | |
extension ViewController: UITableViewDataSource{ | |
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { | |
return monsters.count | |
} | |
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { | |
let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) | |
let monData = monsters[indexPath.row] | |
cell.textLabel?.text = monData.name | |
return cell | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment