NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io

S-1
Create project in xcode , select CoreData while creating.
Create entity and attributes in XCModeldata file, click on entity and then in inspector select codegen as "MANUAL/NONE"
Click on Editor and create NSManagedobject Subclass.

S-2
Navigation Controller
Editor>Embedin>NavigationController>Root will be created
create new ViewController from object library.
design both the ViewController>create Cocoatouch class>Scree1 VC(file attached) and Screen 2 VC(file attached).
attach view controllers to the storyboard interfaces as class

S-3
Add Bar button item in screen1 VC in storyboard change to "ADD"
Ctrl+Drag from button to another VC to create a Segue(select show)

S-4
Create weak outlets and action from addform VC to AddStudentVC(ctrl+drag)from storyboard to VC file

S-5
Create table view in screen1 add tableview prototype cell.craete outlets in screen1 VC file.
add "Cell" as cell reusable identifier in prototype cell

S-6
Ctrl+Drag from tableView to ViewController corner to add UITableViewDataSource and UITableViewDelegate.

S-7
create extension in screen1 VC for UITableViewDataSource and UITableViewDelegate.
error will pop up and fix the the stubs // implement methods
create students/entity object in screen1 VC

S-8
create swift file name it as DBManager>import UIKit instead of foundation.
create class DBManager and create its instance named share.
from Appdelegate file copy persistance and saveContext func. to DBManager(file attached)
import CoreData in DBManager
declare context outside func lazy var context

S-9
in SceneDelegate file remove last line and rewrite context(file attached)

S-10
Create NSFetchRequest method in DBManager(file attach) and return student
in screen1 VC create viewWillAppear method and call fetch method and reloadData
in screen1 VC numberOfRowsInSection method> return students.count
in dequeueReusableCell method define cell(file attach)

S-11
now in AddStudentVC file in onClickAdd method
write code to save data via DBManager.share.saveContext()

S-11
to delete , in screen1 VC after dequeueReusableCell method
at EditingStyle method>EditingStyle.delete(file attached)
write code to delete
==========================================================================================================================
ViewController.swift
----------------------------
// ViewController.swift
// CoreDataCRUD
// Created by bmiit on 5/9/22.
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var studentTable: UITableView!

var students=[Student]()

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}

override func viewWillAppear(_ animated: Bool) {
students=DBManager.share.fetchStudent()
studentTable.reloadData()
}


}

extension ViewController: UITableViewDelegate,UITableViewDataSource
{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return students.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let astudent=students[indexPath.row]
cell.textLabel?.text=astudent.name
cell.detailTextLabel?.text=astudent.school
return cell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCell.EditingStyle.delete
{
do{
try DBManager.share.context.delete(students[indexPath.row])
}
catch{
print("error in deleting")
}
DBManager.share.saveContext()
students.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
}}}
=====================================================================================================================================
AddStudentVC.swift
-------------------------
// AddStudentVC.swift
// CoreDataCRUD
// Created by bmiit on 5/9/22.
import UIKit
class AddStudentVC: UIViewController {
@IBOutlet weak var txtname: UITextField!
@IBOutlet weak var txtstd: UITextField!
@IBOutlet weak var txtschool: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func onClickAdd(_ sender: Any) {
if let name=txtname.text, let std=txtstd.text, let school=txtschool.text
{
let newstudent = Student(context: DBManager.share.context)
newstudent.name=name
newstudent.std=std
newstudent.school=school
DBManager.share.saveContext()
}}}
==========================================================================================================================
AppDelegate.swift
-----------------------
// AppDelegate.swift
// CoreDataCRUD
// Created by bmiit on 5/9/22.
import UIKit
import CoreData
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
return true
}
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {}
}
===========================================================================================================================================
DBManager.swift
---------------------
// DBManager.swift
// CoreDataCRUD
// Created by bmiit on 5/9/22.
import UIKit
import CoreData
class DBManager{
static let share=DBManager()
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "CoreDataCRUD")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error (error), (error.userInfo)")
} })
return container
}()
// MARK: - Core Data Saving support
lazy var context = persistentContainer.viewContext
func saveContext () {
if context.hasChanges {
do {try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error (nserror), (nserror.userInfo)")
}}}
func fetchStudent()->[Student]
{
var student=[Student]()
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: Student.description())
do{
student = try context.fetch(fetchRequest) as! [Student]}
catch{print("fetching error")}
return student
}
}
=======================================================================================================================================
SceneDelegate.swift
-------------------------
// SceneDelegate.swift
// CoreDataCRUD
// Created by bmiit on 5/9/22.
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let _ = (scene as? UIWindowScene) else { return }
}

func sceneDidDisconnect(_ scene: UIScene) {
}

func sceneDidBecomeActive(_ scene: UIScene) {.
}

func sceneWillResignActive(_ scene: UIScene) {
}

func sceneWillEnterForeground(_ scene: UIScene) {
}

func sceneDidEnterBackground(_ scene: UIScene) {
DBManager.share.saveContext()
}
}
=========================================================================================================================================
==========================================================================================================================================
Basic tableView
---------------
//Contact Table View
2 Ways- in storyboard and Programatically


S-1
Add tableView from object library to ViewController>apply constraints>create IBOutlet
@IBOutlet var tableView: UITableview!
or Ctrl+Drag from tableView to ViewController
Add prototype call>add identifier to cell.

S-2
Above viewDidLoad
let names = [
"John Smith","Dan Smith","Jason Smith","Mary Smith"]

IN ViewController file declare in viewDidLoad
tableView.delegate = self
tableView.dataSource = self

after end of class implement their methods
===================================================
extension ViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowat indexPath: IndexPath) {
print("you tapped me!")
)

extension ViewController: UITableViewDataSource {
func tableview(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3 // or names.count()
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableview.dequeueReusableCell (withIdentifier: "cell", for: indexPath)
cell.textLabel?.text="Hello World" // or cell.textLabel?.text=names[indexPath.row]
return cell
}
===============================================================================================================================================================
===============================================================================================================================================================
showAlerts
------------
AlertViewController and Sheets
S-1
Create Button in storyboard and create its action in ViewController
S-2
In ViewController file create function to call AlertViewController
==============================================
@IBAction func didTapButton() {
}
func showAlert() {
let alert = UIAlertController(title: "Title", message: "Hello World", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler: { action in
print("tapped Dismiss") //called when dismiss is pressed - action in
} ) )
present (alert, animated: true)
}
================================================
func showAlertactionsheet() {
let actionSheet = UIAlertController(title: "Title", message: "Hello World", preferredStyle: .actionSheet)
actionSheet.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler: { action in
print("tapped Dismiss") //called when dismiss is pressed - action in
} ) )

actionsheet.addAction(UIAlertAction(title:"One", style: .default, handler: { action in
print("tapped Dismiss")
}))
actionsheet.addAction(UIAlertAction(title: "two", style: .default, handler: { action in
print("tapped Dismiss")
}))
actionsheet.addAction(UIAlertAction(title: "Delete", style: .destructive, handler: { action in
print("tapped Dismiss")
}))

present (actionSheet, animated: true)
}
===============================================================================================================================================================
===============================================================================================================================================================
//Dismissing the keyboard using touchGestureRecognizer
class ViewController: UIViewController {
override func viewDidLoad(O {
super.viewDidLoad()
//when user touch on screen
let tap:UITapGestureRecognizer = UITapGestureRecognizer(target: self,action: #selector(dissmisskeyboard))
self.view.addGestureRecognizer(tap)
}
//dissmiss keyboard
@objc func dissmisskeyboard(){
self.view.endEditing(true)
}
}
     
 
what is notes.io
 

Notes.io is a web-based application for taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000 notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 12 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.