Duplicate code - swift3
swift3 noob like this, please excuse me if this is a stupid question.
I came across this problem several times but couldn't solve it. How can I avoid duplicate code in below.
@IBAction func logOutButton(_ sender: Any) {
var userEntered = usernameText.text!
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
request.predicate = NSPredicate(format: "username = %@", "xyz")
do {
let results = try context.fetch(request)
} catch {
print ("Delete failed")
}
}
@IBAction func submitButton(_ sender: Any) {
var users = [String]()
var userEntered = usernameText.text!
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
let newValue = NSEntityDescription.insertNewObject(forEntityName: "Users", into: context)
newValue.setValue(userEntered, forKey: "username")
request.returnsObjectsAsFaults = false
do {
try context.save()
As you can see, the code below is duplicated in both buttons. How can I avoid this? I tried to write it in a method, but I must be doing something wrong and it is causing a lot of errors.
var userEntered = usernameText.text!
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
thank
+3
source to share
2 answers
Just create a return function that returns NSFetchRequest
.
func getFetchRequest() -> NSFetchRequest {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
return request
}
+1
source to share
Create a function that returns NSFetchRequest
func getRequest() -> NSFetchRequest {
var userEntered = usernameText.text!
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
}
Then your actions will be like
@IBAction func logOutButton(_ sender: Any) {
let request = getRequest()
request.predicate = NSPredicate(format: "username = %@", "xyz")
do {
let results = try context.fetch(request)
} catch {
print ("Delete failed")
}
}
0
source to share