
import UIKit
import CoreData
struct DBRecord {
var user:String
var pass:String
var age:String
}
class ViewController: UIViewController {
@IBOutlet weak var userName: UITextField!
@IBOutlet weak var password: UITextField!
@IBOutlet weak var age: UITextField!
@IBOutlet weak var textView: UITextView!
var appDelegate:AppDelegate!
var context: NSManagedObjectContext!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//1)
appDelegate = UIApplication.shared.delegate as? AppDelegate
//2)
context = appDelegate.persistentContainer.viewContext
// struct Person {
// var name: String
// var surname: String
// var phone: Int
// var isCustomer: Bool
// }
//
// var contacts: [Person] = []
//
// let person1: Person = Person(name: "Jack", surname: "Johnson", phone: 2, isCustomer: false)
// let person2: Person = Person(name: "alex", surname: "a", phone: 3, isCustomer: false)
//
// contacts.append(person1)
// contacts.append(person2)
//
// for contact in contacts {
// print("\(contact.name)")
// }
}
@IBAction func save(_ sender: Any) {
//Steps
// Add Records to Core Data
// The process of adding the records to Core Data has following tasks
//
// 1)Refer to persistentContainer
// 2)Create the context
// 3)Create an entity
// 4)Create new record
// 5)Save values for the records for each key
// //2)
// let context = appDelegate.persistentContainer.viewContext
//3)
let entity = NSEntityDescription.entity(forEntityName: "Users", in: context)
let newUser = NSManagedObject(entity: entity!, insertInto: context)
//4)
newUser.setValue(userName.text, forKey: "username")
newUser.setValue(password.text, forKey: "password")
newUser.setValue(age.text, forKey: "age")
//5)Save
do {
try context.save()
} catch {
print("Failed saving")
}
}
@IBAction func fetch(_ sender: Any) {
//Steps
// Fetch from Core Data
// The process of fetching the saved data from is very easy as well. It has the following task
//
// 1)Prepare the request of type NSFetchRequest for the entity
// 2)Fetch the result from context in the form of array of [NSManagedObject] (Here we can fetch result in type of dictionary, NSManagedObjectID and NSNumber also) //See this "leanne" answer https://stackoverflow.com/questions/40191598/swift-3-nsfetchrequest-distinct-results
// 3)Iterate through an array to get value for the specific key
// Create Fetch Request
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
// request.predicate = NSPredicate(format: "age = %@", "12")
// request.predicate = NSPredicate(format: "age <= %@", "12")
// request.predicate = NSPredicate(format: "age > %@", "12")
// request.predicate = NSPredicate(format: "age < %@ && age > %@", "13", "10")
// request.predicate = NSPredicate(format: "age < %@ || age > %@", "12", "11")
// request.predicate = NSPredicate(format: "%K CONTAINS %@", "username", "u")
// request.predicate = NSPredicate(format: "%K CONTAINS[c] %@", "username", "U")
// request.predicate = NSPredicate(format: "%K CONTAINS[c] %@ AND %K < %i", "username", "U", "age", 12)
// request.predicate = NSPredicate(format: "%K BEGINSWITH[cd] %@", "username", "u")
// request.predicate = NSPredicate(format: "username CONTAINS[cd] %@ AND age < %d", "u", 12)
/*
//Add NSCompoundPredicate
let predicate1 = NSPredicate(format: "age = 12")
// let predicate2 = NSPredicate(format: "%K = %@", "username", "user1")
let predicate2 = NSPredicate(format: "%K = %@ || %K = %@", "username", "user1", "username", "user2")
// request.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate1, predicate2])
// request.predicate = NSCompoundPredicate(notPredicateWithSubpredicate: predicate1)
request.predicate = NSCompoundPredicate(orPredicateWithSubpredicates: [predicate1, predicate2])
*/
// Add Sort Descriptor
// let sortDescriptor = NSSortDescriptor(key: "username", ascending: true)
// let sortDescriptor = NSSortDescriptor(key: "age", ascending: true)
// request.sortDescriptors = [sortDescriptor]
/*
// Create Predicate
request.predicate = NSPredicate(format: "%K == %@", "username", "user")
// Add Sort Descriptor
let sortDescriptor1 = NSSortDescriptor(key: "username", ascending: true)
let sortDescriptor2 = NSSortDescriptor(key: "age", ascending: true)
request.sortDescriptors = [sortDescriptor1, sortDescriptor2]
*/
/*
let nameSortDescriptor = NSSortDescriptor(key: "username", ascending: true)
let priceSortDescriptor = NSSortDescriptor(key: "password", ascending: true)
request.sortDescriptors = [nameSortDescriptor, priceSortDescriptor]
*/
// request.fetchOffset = 5//It will stop first 5 records
// request.fetchLimit = 2//It will fetch only 2 records
// request.fetchBatchSize = 20
//
// To get specific column
// //Link 1): https://stackoverflow.com/questions/46317889/could-not-cast-value-of-type-nsknownkeysdictionary1-to
// //Link 2): https://stackoverflow.com/questions/40191598/swift-3-nsfetchrequest-distinct-results
// request.resultType = .dictionaryResultType
// request.propertiesToFetch = ["username"]//It's get only one cloumn
// request.propertiesToFetch = ["username", "password"]//It's get two columns
// request.returnsDistinctResults = true//To get distinct elements
//
// request.returnsObjectsAsFaultrs = false
do {
let result = try context.fetch(request)
// print(result)
//Procedure 1
//Create arrays to store values
var userArr = [String]()
var passArr = [String]()
var ageArr = [String]()
//Procedure 2
//Create custom type array to store values
var DBArray:[DBRecord] = []//Custom type array (Struct)
for data in result as! [NSManagedObject] {
//Procedure 2
let u = data.value(forKey: "username") as! String
let p = data.value(forKey: "password") as! String
let a = data.value(forKey: "age") as! String
DBArray.append(DBRecord(user: u, pass: p, age: a))
//Procedure 1
userArr.append(data.value(forKey: "username") as! String)
passArr.append(data.value(forKey: "password") as! String)
ageArr.append(data.value(forKey: "age") as! String)
}
if DBArray.count > 0 {
textView.text = "\(DBArray)"
}
for dbrecord in DBArray {
print(dbrecord)
}
} catch {
print("Fetch Failed")
}
}
@IBAction func deleteRecord(_ sender: Any) {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
//request.predicate = NSPredicate(format: "age = %@", "12")
// request.returnsObjectsAsFaults = false
do {
let result = try context.fetch(request)
for data in result as! [NSManagedObject] {
context.delete(data)
do {
try context.save()
} catch {
print("Failed saving")
}
}
} catch {
print("Delete Failed")
}
}
@IBAction func update(_ sender: UIButton) {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
request.predicate = NSPredicate(format: "age = %@", "age1")
do {
let result = try context.fetch(request) as? [NSManagedObject]
if result?.count != 0 { // Atleast one was returned
// In my case, I only updated the first item in results
result![0].setValue("19", forKey: "age")
do {
try context.save()
} catch {
print("Failed saving:\(error)")
}
} else {
print("No recors found...")
}
} catch {
print("Update Failed : \(error)")
}
}
}
No comments:
Post a Comment