(作业)采用多MVC和Core Data构造一个个人信息维护程序

XGBoost实战:从原理到调参,手把手教你提升模型性能(附Python代码) 本文深入解析XGBoost核心原理,并提供一套从数据准备、系统性调参到生产部署的完整实战指南。通过剖析目标函数、正则化项与分裂算法,帮助读者理解参数背后的数学逻辑,并利用交叉验证、早停法及自动化工具(如Optuna)高效提升模型性能。文中附有详尽的Python代码示例,涵盖类别特征处理、缺失值应对、不平衡数据调整及模型可视化等高级技巧。 阅读详情

这次作业要用到一个新的框架,话不多说,先上需求
这里写图片描述
然后看看博主实现的程序吧
这里写图片描述

现在我们就开始一步一步地实现这个程序吧。
首先从工程的创建开始,因为要使用Core Data,所以需要在创建工程时将Use Core Data打上勾,这样的话系统会自动帮我们生成一些代码和文件
这里写图片描述

这里写图片描述
这个homework.xcdatamodeld文件就是系统帮我们生成的,再看看AppDelegate.swift文件,会发现里面多了一些代码

// MARK: - Core Data stack

lazy var persistentContainer: NSPersistentContainer = {
    /*
     The persistent container for the application. This implementation
     creates and returns a container, having loaded the store for the
     application to it. This property is optional since there are legitimate
     error conditions that could cause the creation of the store to fail.
    */
    let container = NSPersistentContainer(name: "homework")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

            /*
             Typical reasons for an error here include:
             * The parent directory does not exist, cannot be created, or disallows writing.
             * The persistent store is not accessible, due to permissions or data protection when the device is locked.
             * The device is out of space.
             * The store could not be migrated to the current model version.
             Check the error message to determine what the actual problem was.
             */
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()

// MARK: - Core Data Saving support

func saveContext () {
    let context = persistentContainer.viewContext
    if context.hasChanges {
        do {
            try context.save()
        } catch {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            let nserror = error as NSError
            fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
        }
    }
}

其中persistentContainer属性和saveContext()方法会在后面用到。

然后我们就需要在数据库中添加自己的表了。因为这里使用的是Core Data,我们就不需要使用SQL语句来创建表或者插入数据了,直接在xcode里面通过编辑器就可以创建实体类了,我们这里创建一个叫Person的实体,它包含两个属性name和age,操作步骤如下:
这里写图片描述

从上面的运行图可以看出,博主这里使用了三个界面,Persons展示数据库中已经存在的界面;Add和Edit是同一个界面,负责增加或修改Person的信息;Search界面做一些特定的查询。所以出了系统自带的ViewController.swift文件之外,我们还需要再创建两个控制器文件,InsertViewController.swift文件和SearchViewController.swift文件。

我们先来实现InsertViewController.swift的功能,首先我们需要两个文本输入框,一个输入名字,一个输入年龄,所以需要声明两个属性,而且需要声明一个记录下标的属性,这个属性保存前一个界面传入的点击的cell的下标

var row: Int?
var nameTextField: UITextField!
var ageTextField: UITextField!

因为要使用Core Data,所以我们需要导入库

import CoreData

然后构建我们的界面,首先将两个文本输入框添加到视图上,然后在navigationbar上添加一个完成的按钮,最后再根据是否传入的了下标来设置视图的标题(如果没有传入下标,就是添加数据,如果传入了,就是修改数据)
所以最终的viewDidLoad方法内容如下

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    self.view.backgroundColor = UIColor.white

    nameTextField = UITextField(frame: CGRect(x: 20, y: 100, width: 300, height: 44))
    nameTextField.layer.borderWidth = 1
    self.view.addSubview(nameTextField)

    ageTextField = UITextField(frame: CGRect(x: 20, y: 200, width: 300, height: 44))
    ageTextField.layer.borderWidth = 1
    self.view.addSubview(ageTextField)

    let btn = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(done))
    self.navigationItem.rightBarButtonItem = btn

    if row == nil {
        self.title = "Add"
    } else {
        self.title = "Edit"
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let context = appDelegate.persistentContainer.viewContext
        let request: NSFetchRequest<Person> = Person.fetchRequest()
        if let persons = try? context.fetch(request) {
            nameTextField.placeholder = persons[row!].name
            ageTextField.placeholder = String(persons[row!].age)
        }
    }
}

在判断为修改数据时,我们需要给两个文本输入框设置占位符,这里就使用了Core Data的查询。在查询Core Data中的数据时,我们需要先获取到程序代理,也就是AppDelegate,然后获取代理中的上下文,这个就需要AppDelegate.swift中新生成的persistentContainer了。在获取到context之后,需要初始化一个查询的请求,这个请求用于指定查找哪个实体的数据,并且可以设置一些查询的条件,详细会在Search界面多讲解,在调用context的fetch后,会返回实体的数组,我们就根据传入的下标,来获取数组中的元素,并将其值设置为textfield的placeholder。

在构建完成界面之后,我们就需要实现done按钮的功能。

@objc func done() {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext

    let name = self.nameTextField.text!
    let age = Int16(self.ageTextField.text!)

    if row == nil {
        if !name.isEmpty && age != nil {
            let person = Person(context: context)
            person.name = name
            person.age = age!
        }
    } else {
        let request: NSFetchRequest<Person> = Person.fetchRequest()
        if let persons = try? context.fetch(request) {
            if !name.isEmpty {
                persons[row!].name = name
            }
            if age != nil {
                persons[row!].age = age!
            }
        }
    }
    appDelegate.saveContext()
    self.navigationController?.popViewController(animated: true)
}

在这个方法中,我们先获取到context(上下文),然后取出textfield中填的数据,再判断是否是添加数据做不同的操作,
如果是添加数据的话,就用context初始化一个Person实体,设置其值,最后保存数据即可。
如果是修改数据的话,就需要将数据库中存在的数据查出,然后再根据传入的下标找到实体实例,修改其值,最后保存数据。
在将数据保存到数据库中之后,就关闭本界面,返回上一个界面。到这里,InsertViewController.swift中的内容就实现完了。

然后我们实现Search界面,也就是SearchViewController的内容。
因为这个界面中使用了UITableView,所以需要实现其代理和数据源

class SearchViewController: UIViewController, UITableViewDelegate, UITableViewDataSource

因为要使用Core Data,所以我们需要导入库

import CoreData

然后我们需要声明或初始化以下属性

var nameTextField: UITextField!
var ageTextField: UITextField!
var tableView: UITableView!
var persons = [Person]()
let appDelegate = UIApplication.shared.delegate as! AppDelegate

其中前三个是界面显示的组件,第四个保存查询出的数据,最后一个获取应用的代理(用于数据查询)。

然后在viewDidLoad方法中构建界面

self.view.backgroundColor = UIColor.white
self.title = "Search"

nameTextField = UITextField(frame: CGRect(x: 10, y: 100, width: 200, height: 44))
nameTextField.layer.borderWidth = 1
self.view.addSubview(nameTextField)

let nameBtn = UIButton(frame: CGRect(x: 250, y: 100, width: 100, height: 44))
nameBtn.setTitle("按名字查找", for: .normal)
nameBtn.setTitleColor(UIColor.cyan, for: .normal)
nameBtn.setTitleColor(UIColor.brown, for: .highlighted)
nameBtn.addTarget(self, action: #selector(searchWithName), for: .touchUpInside)
self.view.addSubview(nameBtn)

ageTextField = UITextField(frame: CGRect(x: 10, y: 150, width: 200, height: 44))
ageTextField.layer.borderWidth = 1
self.view.addSubview(ageTextField)

let ageBtn = UIButton(frame: CGRect(x: 250, y: 150, width: 100, height: 44))
ageBtn.setTitle("按年龄查找", for: .normal)
ageBtn.setTitleColor(UIColor.cyan, for: .normal)
ageBtn.setTitleColor(UIColor.brown, for: .highlighted)
ageBtn.addTarget(self, action: #selector(searchWithAge), for: .touchUpInside)
self.view.addSubview(ageBtn)

tableView = UITableView(frame: CGRect(x: 0, y: 200, width: self.view.frame.width, height: self.view.frame.height - 200))
tableView.delegate = self
tableView.dataSource = self
self.view.addSubview(tableView)

接下来就该实现两个按钮的功能,分别实现按照名字查找和按照年龄查找
首先实现按名字查找

@objc func searchWithName() {
    ageTextField.text = ""
    let context = appDelegate.persistentContainer.viewContext

    let name = nameTextField.text

    let request: NSFetchRequest<Person> = Person.fetchRequest()
    if name != nil {
        request.predicate = NSPredicate(format: "name = %@", name!)
    }
    if let persons = try? context.fetch(request) {
        self.persons = persons
        tableView.reloadData()
    }
}

在这个方法中,我们先通过应用代理(appDelegate)获取上下文,然后初始化一个查询请求,该请求为Person的查询请求,并设置查询的谓词(也就是查询的条件),最后将查询的结构保存在数组当中。

按年龄查找的代码类似

@objc func searchWithAge() {
    nameTextField.text = ""
    let context = appDelegate.persistentContainer.viewContext

    let age = Int16(ageTextField.text!)

    let request: NSFetchRequest<Person> = Person.fetchRequest()
    if age != nil {
        request.predicate = NSPredicate(format: "age = %d", age!)
    }
    if let persons = try? context.fetch(request) {
        self.persons = persons
        tableView.reloadData()
    }
}

在实现这两个方法之后,我们就需要实现UITableViewDataSource中要求的两个方法

// MARK: data source

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return persons.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")

    if cell == nil {
        cell = UITableViewCell(style: .subtitle, reuseIdentifier: "Cell")
    }

    cell?.textLabel?.text = persons[indexPath.row].name
    cell?.detailTextLabel?.text = String(persons[indexPath.row].age)

    return cell!
}

到这里,我们的SearchViewController.swift就实现完成了,最后我们来实现主界面。
在实现主界面之前,我们需要将其放入导航栏控制器当中,所以在AppDelegate.swift的func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool方法中添加下面一行代码

window?.rootViewController = UINavigationController(rootViewController: ViewController())

这句代码是将导航栏控制器作为window的根视图控制器,并设置该导航栏控制器的根视图控制器为ViewController

然后回到我们的ViewController.swift,声明或初始化以下三个属性

var tableView: UITableView!
var personArray = [Person]()
let appDelegate = UIApplication.shared.delegate as! AppDelegate

第一个属性为视图中的表,第二个保存数据库中的数据,第三个为应用代理

因为要使用Core Data,所以我们需要导入库

import CoreData

然后想导航栏上添加两个按钮,一个添加,一个查询,并将表视图添加到视图上

self.title = "Persons"
self.view.backgroundColor = UIColor.white

tableView = UITableView(frame: self.view.frame)
tableView.delegate = self
tableView.dataSource = self
self.view.addSubview(tableView)

let searchBtn = UIBarButtonItem(barButtonSystemItem: .search, target: self, action: #selector(search))
self.navigationItem.leftBarButtonItem = searchBtn

let addBtn = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(add))
self.navigationItem.rightBarButtonItem = addBtn

接下来实现两个导航栏按钮的功能,分别进入两个不同的控制器

@objc func search() {
    let viewController = SearchViewController()
    self.navigationController?.pushViewController(viewController, animated: true)
}

@objc func add() {
    let viewController = InsertViewController()
    self.navigationController?.pushViewController(viewController, animated: true)
}

现在我们需要实现UITableViewDataSource中的两个方法

// MARK: data source

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return personArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")

    if cell == nil {
        cell = UITableViewCell(style: .subtitle, reuseIdentifier: "Cell")
        cell?.accessoryType = .disclosureIndicator
    }

    cell?.textLabel?.text = personArray[indexPath.row].name
    cell?.detailTextLabel?.text = String(personArray[indexPath.row].age)

    return cell!
}

到这里,基本的东西已经实现,但界面没有显示数据,并且不能修改和删除数据。

那我们先来实现数据的显示,因为我们的数据是在界面加载之后显示,并且从添加界面返回之后需要重新加载一次数据,所以我们将数据的显示放到viewWillAppear方法中,这个方法在每一次界面即将显示时就会调用一次,不想viewDidLoad只在第一次加载界面时才调用

override func viewWillAppear(_ animated: Bool) {
    let context = appDelegate.persistentContainer.viewContext

    let request: NSFetchRequest<Person> = Person.fetchRequest()

    if let persons = try? context.fetch(request) {
        personArray = persons
    }
    tableView.reloadData()
}

这个方法的内容非常简单,先从数据库中查找出所有数据,并更新表视图即可。这样,我们的数据就能正常显示到界面上了,现在我们实现点击cell,修改其相应的数据。
这时,我们就需要用到UITableViewDelegate中的方法了,

// MARK: delegate

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let viewController = InsertViewController()
    viewController.row = indexPath.row
    self.navigationController?.pushViewController(viewController, animated: true)
}

在这个方法中,我们先创建一个编辑控制器的实例,然后将cell的下标传入,最后显示界面。这时,我们就实现了编辑数据了。最后还差一个功能——删除数据。

在实现删除数据时,我们需要先调用UITableViewDelegate中的方法,设置每个cell的编辑样式,我们将其所有都设置为删除

func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
    return .delete
}

然后实现UITableViewDataSource中的提交编辑方法。

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        personArray.remove(at: indexPath.row)
        tableView.reloadData()

        DispatchQueue.global().async {
            let context = self.appDelegate.persistentContainer.viewContext

            let request: NSFetchRequest<Person> = Person.fetchRequest()
            if let persons = try? context.fetch(request) {
                context.delete(persons[indexPath.row])
                self.appDelegate.saveContext()
            }
        }
    }
}

在该方法中,我们判断单元格是否可以删除,在将数据数组中相应的数据删除,然后更新表视图。最后我们使用多线程的方式删除数据库中的数据,这样可以减少界面的卡顿。CoreData删除数据的方式很简单,需要先找到待删除的实体实例,然后调用context(上下文)的delete方法即可,它会帮你找到相应的实体,然后从数据库中删除。

到这里,我们的整个程序就实现完成了,最后贴一下所有的代码吧。

AppDelegate.swift

import UIKit
import CoreData

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        window?.rootViewController = UINavigationController(rootViewController: ViewController())

        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        // Saves changes in the application's managed object context before the application terminates.
        self.saveContext()
    }

    // MARK: - Core Data stack

    lazy var persistentContainer: NSPersistentContainer = {
        /*
         The persistent container for the application. This implementation
         creates and returns a container, having loaded the store for the
         application to it. This property is optional since there are legitimate
         error conditions that could cause the creation of the store to fail.
        */
        let container = NSPersistentContainer(name: "homework")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

    // MARK: - Core Data Saving support

    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }

}

ViewController.swift

import UIKit
import CoreData

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var tableView: UITableView!
    var personArray = [Person]()
    let appDelegate = UIApplication.shared.delegate as! AppDelegate

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        self.title = "Persons"
        self.view.backgroundColor = UIColor.white

        tableView = UITableView(frame: self.view.frame)
        tableView.delegate = self
        tableView.dataSource = self
        self.view.addSubview(tableView)

        let searchBtn = UIBarButtonItem(barButtonSystemItem: .search, target: self, action: #selector(search))
        self.navigationItem.leftBarButtonItem = searchBtn

        let addBtn = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(add))
        self.navigationItem.rightBarButtonItem = addBtn

    }

    override func viewWillAppear(_ animated: Bool) {
        let context = appDelegate.persistentContainer.viewContext

        let request: NSFetchRequest<Person> = Person.fetchRequest()

        if let persons = try? context.fetch(request) {
            personArray = persons
        }
        tableView.reloadData()
    }

    @objc func search() {
        let viewController = SearchViewController()
        self.navigationController?.pushViewController(viewController, animated: true)
    }

    @objc func add() {
        let viewController = InsertViewController()
        self.navigationController?.pushViewController(viewController, animated: true)
    }

    // MARK: delegate

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let viewController = InsertViewController()
        viewController.row = indexPath.row
        self.navigationController?.pushViewController(viewController, animated: true)
    }

    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
        return .delete
    }

    // MARK: data source

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return personArray.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")

        if cell == nil {
            cell = UITableViewCell(style: .subtitle, reuseIdentifier: "Cell")
            cell?.accessoryType = .disclosureIndicator
        }

        cell?.textLabel?.text = personArray[indexPath.row].name
        cell?.detailTextLabel?.text = String(personArray[indexPath.row].age)

        return cell!
    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            personArray.remove(at: indexPath.row)
            tableView.reloadData()

            DispatchQueue.global().async {
                let context = self.appDelegate.persistentContainer.viewContext

                let request: NSFetchRequest<Person> = Person.fetchRequest()
                if let persons = try? context.fetch(request) {
                    context.delete(persons[indexPath.row])
                    self.appDelegate.saveContext()
                }
            }
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

InsertViewController.swift

import UIKit
import CoreData

class InsertViewController: UIViewController {

    var row: Int?
    var nameTextField: UITextField!
    var ageTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.view.backgroundColor = UIColor.white

        nameTextField = UITextField(frame: CGRect(x: 20, y: 100, width: 300, height: 44))
        nameTextField.layer.borderWidth = 1
        self.view.addSubview(nameTextField)

        ageTextField = UITextField(frame: CGRect(x: 20, y: 200, width: 300, height: 44))
        ageTextField.layer.borderWidth = 1
        self.view.addSubview(ageTextField)

        let btn = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(done))
        self.navigationItem.rightBarButtonItem = btn

        if row == nil {
            self.title = "Add"
        } else {
            self.title = "Edit"
            let appDelegate = UIApplication.shared.delegate as! AppDelegate
            let context = appDelegate.persistentContainer.viewContext
            let request: NSFetchRequest<Person> = Person.fetchRequest()
            if let persons = try? context.fetch(request) {
                nameTextField.placeholder = persons[row!].name
                ageTextField.placeholder = String(persons[row!].age)
            }
        }
    }

    @objc func done() {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let context = appDelegate.persistentContainer.viewContext

        let name = self.nameTextField.text!
        let age = Int16(self.ageTextField.text!)

        if row == nil {
            if !name.isEmpty && age != nil {
                let person = Person(context: context)
                person.name = name
                person.age = age!
            }
        } else {
            let request: NSFetchRequest<Person> = Person.fetchRequest()
            if let persons = try? context.fetch(request) {
                if !name.isEmpty {
                    persons[row!].name = name
                }
                if age != nil {
                    persons[row!].age = age!
                }
            }
        }
        appDelegate.saveContext()
        self.navigationController?.popViewController(animated: true)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

SearchViewController.swift

import UIKit
import CoreData

class SearchViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var nameTextField: UITextField!
    var ageTextField: UITextField!
    var tableView: UITableView!
    var persons = [Person]()
    let appDelegate = UIApplication.shared.delegate as! AppDelegate

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        self.view.backgroundColor = UIColor.white
        self.title = "Search"

        nameTextField = UITextField(frame: CGRect(x: 10, y: 100, width: 200, height: 44))
        nameTextField.layer.borderWidth = 1
        self.view.addSubview(nameTextField)

        let nameBtn = UIButton(frame: CGRect(x: 250, y: 100, width: 100, height: 44))
        nameBtn.setTitle("按名字查找", for: .normal)
        nameBtn.setTitleColor(UIColor.cyan, for: .normal)
        nameBtn.setTitleColor(UIColor.brown, for: .highlighted)
        nameBtn.addTarget(self, action: #selector(searchWithName), for: .touchUpInside)
        self.view.addSubview(nameBtn)

        ageTextField = UITextField(frame: CGRect(x: 10, y: 150, width: 200, height: 44))
        ageTextField.layer.borderWidth = 1
        self.view.addSubview(ageTextField)

        let ageBtn = UIButton(frame: CGRect(x: 250, y: 150, width: 100, height: 44))
        ageBtn.setTitle("按年龄查找", for: .normal)
        ageBtn.setTitleColor(UIColor.cyan, for: .normal)
        ageBtn.setTitleColor(UIColor.brown, for: .highlighted)
        ageBtn.addTarget(self, action: #selector(searchWithAge), for: .touchUpInside)
        self.view.addSubview(ageBtn)

        tableView = UITableView(frame: CGRect(x: 0, y: 200, width: self.view.frame.width, height: self.view.frame.height - 200))
        tableView.delegate = self
        tableView.dataSource = self
        self.view.addSubview(tableView)

    }

    @objc func searchWithName() {
        ageTextField.text = ""
        let context = appDelegate.persistentContainer.viewContext

        let name = nameTextField.text

        let request: NSFetchRequest<Person> = Person.fetchRequest()
        if name != nil {
            request.predicate = NSPredicate(format: "name = %@", name!)
        }
        if let persons = try? context.fetch(request) {
            self.persons = persons
            tableView.reloadData()
        }
    }

    @objc func searchWithAge() {
        nameTextField.text = ""
        let context = appDelegate.persistentContainer.viewContext

        let age = Int16(ageTextField.text!)

        let request: NSFetchRequest<Person> = Person.fetchRequest()
        if age != nil {
            request.predicate = NSPredicate(format: "age = %d", age!)
        }
        if let persons = try? context.fetch(request) {
            self.persons = persons
            tableView.reloadData()
        }
    }

    // MARK: data source

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return persons.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")

        if cell == nil {
            cell = UITableViewCell(style: .subtitle, reuseIdentifier: "Cell")
        }

        cell?.textLabel?.text = persons[indexPath.row].name
        cell?.detailTextLabel?.text = String(persons[indexPath.row].age)

        return cell!
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
SAP UI5 百科全书的目录 笔者 12 年 SAP UI5 开发岁月中写下的 595 篇 SAP UI5 学习笔记,全部收录到《SAP UI5 百科全书》专栏中去,目录如下。请大家按照自己的学习需要,根据关键字搜索到对应的文章,然后进行学习。 阅读详情

相关推荐

【滤波跟踪】多雷达协同下的多目标跟踪:航迹管理优化与卡尔曼滤波融合策略

本文深入探讨了多雷达协同下的多目标跟踪技术,聚焦于航迹管理优化与卡尔曼滤波融合策略两大核心。通过分析分布式融合架构、航迹关联算法(如匈牙利算法)以及应对非线性与机动目标的扩展卡尔曼滤波(EKF)与无迹卡尔曼滤波(UKF)等方法,旨在解决多源信息融合难题,提升复杂环境下目标跟踪的精度与鲁棒性。

weixin_29214199的博客 286

第六次作业——MVC

这里先简单的介绍一下我对MVC的理解。M——model(模型)V——view(视图)C——controller(控制器)视图很好理解,它就是我们JSP页面,用来显示页面内容的,因此称为视图;模型指的就是一些bean和dao,主要是用来存储数据和对数据的一些业务处理;controller则指的就是我们的servlet,它的作用是在模型和视图中间起到一个调度的作用,也就是它决定我们需要将哪些数据显示在哪个页面上。这里借用一下这张图,表达一下它们之间的关系。

m0_62513791的博客 225

游戏资源解包神器NSCB实战:手把手教你提取Switch游戏视频(nsm转MP4)

本文详细介绍了如何使用NSCB工具链从Switch游戏中提取nsm视频和hca音频资源,并将其转换为可编辑的MP4和MP3格式。通过NSC Builder、CriPakTools等工具的分步操作指南,帮助内容创作者高效获取游戏资源,同时提供音视频同步合成、批量处理等高级技巧,为创意素材制作提供完整解决方案。

weixin_29197835的博客 915

第七次作业--MVC

EL是指Expression Language,它是一种用于在JSP页面中访问JavaBean属性和其他对象的简洁语言。EL可以帮助开发人员避免使用脚本片段来访问Java对象,从而简化了JSP页面的编写。JSTL是指JSP Standard Tag Library,它是一组自定义标签,用于简化在JSP页面中执行常见任务的操作。包括条件语句、循环和格式化等。JSTL标签库提供了比Java代码更简单且易于维护的方式来处理这些任务。通过上述概念,大致可以明白EL和JSTL都是用来简化JSP页面的。

qq_65688750的博客 243

对比实验系列:Efficientdet环境配置及训练个人数据集

可以通过下方链接下载Efficientdet源码。

Yayisheng的博客 4587

URScript介绍

优傲机器人(Universal Robots)是丹麦工业协作机器人制造商,2005年成立,2015年被泰瑞达收购。其自研编程语言URScript基于Python语法,专为机器人控制优化,支持运动指令、IO控制等功能,具有类Python的简洁语法和实时性特点。URScript提供丰富的API,支持变量赋值、条件判断、循环及函数定义等编程结构,参数按值传递。用户可通过该语言在Polyscope界面编写程序,实现自动化任务。目前优傲在全球20多个办事处为多国客户提供服务。

谢谢大家的关注和点赞!这里只有纯纯的知识干货,没有一句废话。希望能实实在在帮到大家~要是觉得有用,别忘了给我点支持哟,你 608

大作业练习:用Asp.net Mvc4做一个:学生考试成绩管理系统-简易版

大作业名称:学生考试成绩管理系统-简易版 总共分为4个阶段: 第一阶段: 完成原型版V1.0核心业务功能,包括: A.基础信息维护功能: 1.班级信息维护功能 2.学生信息维护功能 B.分值信息维护功能 依赖关系说明:分值信息依赖于学生信息,学生信息依赖于班级信息 第一阶段V1.0原型版 演示地址 :http://demo.exesoft.cn:9191 第一阶段V1.0源码获得...

格码老师教编程 4330

【100%通过率】华为od统一考试B卷【查找接口成功率最优时间段】Python 实现

服务之间交换的接口成功率作为服务调用关键质量特性,某个时间段内的接口失败率使用一个数组表示,数组中每个元素都是单位时间内失败率数值,数组中的数值为0~100的整数, 给定一个数值(minAverageLost)表示某个时间段内平均失败率容忍值,即平均失败率小于等于minAverageLost,找出数组中最长时间段,如果未找到则直接返回NULL。

MISAYAONE的博客 5875

CoreData学习记录一

先来无事,学习了一下CoreData。我对CoreData的理解:CoreData是一个很强大的东西,如果按照层次来划分,他应该处于sqlite之上,应该说位于MVC的model层。有了它,我们可以很自然地和数据库打交道,避免了繁琐的sql语句. 下面这些图是复制别人的,最下面的代码是出自本人之手 Core Data的核心——托管对象 托管对象是要存储到数据库中的对象的一

jijunyuan_11109的专栏 2181

图机器学习(1)——图论基础

图 (Graph) 是一种描述实体间关系的数学结构,几乎在各个领域都有应用。例如,社交网络就是图,其中用户之间的连接取决于一个用户是否“关注”另一个用户。图论,即对图的研究,一直以来广受关注,包含了大量算法、性质分析方法和数学模型,以解析复杂系统的行为特征。本节将介绍图数据结构的核心概念,通过理论阐述与实例演示相结合的方式,理解基础理论用以实践应用。重点介绍用于创建、操作和研究复杂网络结构与功能的 Python 库。

盼小辉丶的博客 9498

杰理SDK入门教程(一):SDK的四种编译方式的使用

杰理SDK提供了四种主要编译方式:1) JL Studio官方IDE,适合初学者;2) VS Code轻量级编辑器,需在SDK根目录打开;3) 命令行/脚本编译,灵活支持自动化;4) Code::Blocks开源IDE。每种方式都有详细操作指南,开发者可根据需求选择,初学者推荐从JL Studio开始熟悉编译流程。环境配置注意事项和编译成功标识均有明确说明,确保开发效率。

qq_42014563的博客 1171

(初识MVC Core)八、发布

1.部署方式 1)FDD(Framework-dependent) 说明:类似IIS网站类的部署,服务器上面必须安装好Framework环境,只发布自己程序文件生成的文件 优势: ①无需配置目标系统 ②部署的文件很小 ③.NET Core被共享使用 劣势: ①必须预先安装.NET Core ②可能存在兼容性问题 2)SCD(Self-Contained),...

angyi6424的博客 276

【DRAM存储器六十六】DDR5介绍--训练相关之CA/CS Training

详述DDR5 CA/CS training过程细节

highman110的博客 221

.netMvc项目作业

1:Ajax提交到后台参数传递可以单个传递也可以对象传递,怎么写? 单个传递 var userName="Lishi"; $.ajax({ url:"/控制器/方法名?userName"+userName, type:"post", suncess:function(orever){ if(){ }else{ } } }) 对象传递: var date ={} var use...

weixin_45268648的博客 234

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

ASP.NET MVC3 制作个人简介WEB应用程序

一晃开学快一个月了,不知道各位同学这段时间有没有作品产生呢 这里更大家showshow我制作的个人简介,vcard 下面预览图 在线预览 戳我下载源代码(需要vs2010&2008 SQLEXPRESS r2的数据库)不好意思啊,发现r2数据库极度不兼容啊..所以其他版本数据库的请用db.sql创建数据库 测试注意路由规则: http://loc...

denggua5671的博客 482

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

【学习笔记】MVC Core 日志使用

日志六种级别: Trace=0,Debug=1,Information=2,Waring=3,Error=4,Critical=5 日志使用: 构造方法注入 ILogger logger private ILogger _logger; public HomeController(ILogger&amp;lt;HomeController&amp;gt; logger) {...

tianjm的博客 422

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

MVC模式的web应用大作业,有没有人帮帮可怜的孩子

一、作业题目: 自拟题目(采用MVC模式完成一个Web应用),题材自选 二、作业要求及评分标准: 1、作业基本要求 (1)涵盖主要知识点:Servlet技术、JSP技术、会话技术以及HTML、XML和数据库的使用等; (2)应用定位:Web应用主题明确、结构清晰、功能可实现。 (3)需求分析、功能设计及实现:画出流程图、MVC模型图等。 (4)数据库(如果使用):画出E-R图,表结构图。 (5)评...

NathanielChenZY的博客 621

Swift4.0 Codable踩坑之派生类数据的保存

本以为之前使用Codable的过程中踩的坑已经够多了,今天博主有遇到一个坑,调了一个下午才解决,问题不大,但是中文的技术文里都很少涉及这个问题。问题描述:遵循了Codable协议的自定义类,派生出的子类JSON化与反JSON化。简单来说,就是这儿有一个类遵循了Codable协议,其自身可以很方便地使用JSONEncoder和JSONDecoder来JSON化和反JSON化。但是子类就不是那么方便了。

麻豆_matou 6659

Swift使用极光推送JPush的Demo

JPushDemo github项目地址 需要导入JPush框架,可以使用cocoapod导入,也可以手动导入 环境配置 配置环境可以参考极光推送的官方文档: iOS 证书设置指南 iOS SDK 集成指南 iOS SDK API 使用说明 待环境配置好了之后,就可以进入极光推送开始推送消息了 极光推送首页 推送使用示例如下: 发送通知 发送自定义消息 代码...

麻豆_matou 5651

Swift从相册选择图片,图文混排并且可以保存、上传数据

博主最近突发奇想想做一个自己的日记本App,在过程中遇到了一些坑,摸索了很久才做出一个简单的日记本功能。先来看看一下效果吧: 先来说说这次用到的一些东西吧: 1、UIImagePickerController:用来获取Photos里面的照片 2、UITexeView:用来做图文混排 3、NSKeyedArchiver和NSKeyedUnarchiver:保存和读取数据 具体的一些细节在过程

麻豆_matou 4002

(作业)Swift类的属性与方法

话不多说,先贴作业要求 因为Person类需要一个枚举类型的gender,所以先定义枚举 //性别的枚举 enum Gender: Int { case male //男性 case female //女性 case unknow //未知 //重载>操作符,方便后面排序使用 static func >(lhs: Ge

麻豆_matou 3192

Swift中UIScrollView与自定义上下滑动手势冲突

今天博主在封装下拉刷新时遇到了这个问题,在给UIScrollView添加UIPanGestureRecognizer时UIScrollView无法滑动了。博主也试了UITableView和UICollectionView,也出了同样的问题。在网上找了很久,终于解决了这个问题,只需要扩展UIScrollView使它遵循UIGestureRecognizerDelegate,并实现其中的一个方法就可以

麻豆_matou 2999

(作业)animation、transition、UIDynamicAnimator

第二个作业要求,先来看看吧,很有趣的一些动画效果 看要求,a和b都不是很麻烦,之前博主自学的时候接触过,第三个接触不多,老师上课时演示的时候有点着迷了,因为,如果有了这个UIDynamicAnimator,那么愤怒的小鸟就不是很难实现的游戏了(有这么神么?后面再介绍吧) 关于UIDynamicAnimator,CSDN的前辈写得很不错先来看看第一个用animation实现视图位置、大小、转换

麻豆_matou 2942

字符串转换为整型

在Swift中,字符串转换为整型的方法有两种,我们在这里比较一下这两种方法的区别: 1、使用强制类型转换,代码如下:var str = "1234" var integer = Int(str) print(integer) // 输出1234 但如果换一个字符串 var str = "123,4" var integer = Int(str) print(intege

麻豆_matou 2823

Swift自定义类的存储

在Swift开发中,许多时候会涉及到存储自定义的类,不管是存储到本地文件还是远程服务器,都会涉及到编码和解码的问题。下面就来介绍一下在Swift中怎么存储自定义的类。 在Swift中存储自定义的类有两种方法,一种是Swift 3.0版本的NSCoding,还有一种是Swift 4.0版本的Codable。我们就两种方法来谈谈其中的区别吧。Swift 3.0: NSCoding在NSCoding这个

麻豆_matou 2667

(作业)TableView、Delegate、DataSource

来来来,继续作业系列的博客,老规矩了,直接上要求 这次作业涉及到iOS开发中最常用的一个UI组件UITableView,App Store中的几乎所有工具型和应用型App都使用了UITableView,而初学UITableView又不是那么容易,因为它涉及到很多代理和数据源的问题,但用熟练了,会觉得它非常地方便。 废话不多说了,先来完成要求吧,在这个过程中,博主会讲解一些细节方面的东西。首先是需

麻豆_matou 2318
上一篇: (作业)使用多线程实现一个网络服务访问程序
下一篇: React Native实现注册和登录
麻豆_matou
博客等级 码龄10年 41粉丝 46原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址