3
swift3 noob在這裏所以請原諒我,如果這是一個愚蠢的問題。代碼重複 - swift3
我幾次遇到過這個問題,但一直無法解決它。我如何避免下面的代碼重複。
@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()
正如你可以看到下面的代碼在兩個按鈕中都重複。我怎樣才能避免這種情況?我試圖用一種方法來編寫它,但我必須做出錯誤的事情,並引發很多錯誤。
var userEntered = usernameText.text!
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
謝謝
請出示你試過,你做了什麼錯誤。 – shallowThought
爲什麼不把你正在使用的代碼多次放入一個函數然後調用該函數? –
使用'NSManagedObject'子類,它避免了很多樣板代碼。然後你可以寫'let request = Users.fetchRequest()' – vadian