研究应用场景
根据不同应用场景选择
1、如果不需要持久化存储,那么单例模式就是最优选择
可以参考下面例子
SwiftUI数据如何在App中的不同视图和类直接调用
2、需要持久化,但不会SQL
建议使用xcode自带的CoreData,优势是原生,不用写SQL语句就可以实现数据的增删改查。可以参考下面例子:
3、需要高性能的查询
SwiftUI 数据之List显示Sqlite数据库内容(2020年教程)
数据存储方案 CoreData vs Sqlite
1、用CoreData理想的模式
class Member {
var name = ""
var type = ""
init(){
}
init(user: User) {
self.name = user.name!
self.type = user.type!
}
}
理想的调用方式
Text("欢迎用户:\(self.uMgr.currentUser.name)")
Text("\(self.uMgr.currentUser.type)")
2、用Sqlite的理想模式
class SQLandmark: SQLTable {
var id = -1
var name = ""
var imageName = ""
override var description:String {
return "id: \(id), name: \(name)"
}
static func customTables() ->String {
return "landmark"
}
}
更优雅简单的调用方式
let sqLandmarkData: [SQLandmark] = SQLandmark.rows(order:"id ASC")
CoreData 和 Sqlite工具区别
1、CoreData 使用Xcode即可
2、Sqlite建议使用Navicat
CoreData增删改查模式
1、获取数据
let appDelegate = UIApplication.shared.delegate as? AppDelegate
managedContext = appDelegate?.persistentContainer.viewContext
insertSampleData()
let request: NSFetchRequest<BowTie> = BowTie.fetchRequest()
let firstTitle = segmentedControl.titleForSegment(at: 0)!
request.predicate = NSPredicate(format: "%K = %@", argumentArray: [#keyPath(BowTie.searchKey), firstTitle])
do {
let results = try managedContext.fetch(request)
currentBowTie = results.first
populate(bowtie: results.first!)
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
2、插入数据
func insertSampleData() {
let fetch: NSFetchRequest<BowTie> = BowTie.fetchRequest()
fetch.predicate = NSPredicate(format: "searchKey != nil")
let count = try! managedContext.count(for: fetch)
if count > 0 {
// SampleData.plist data already in Core Data
return
}
let path = Bundle.main.path(forResource: "SampleData", ofType: "plist")
let dataArray = NSArray(contentsOfFile: path!)!
for dict in dataArray {
let entity = NSEntityDescription.entity(forEntityName: "BowTie", in: managedContext)!
let bowtie = BowTie(entity: entity, insertInto: managedContext)
let btDict = dict as! [String: Any]
bowtie.id = UUID(uuidString: btDict["id"] as! String)
bowtie.name = btDict["name"] as? String
bowtie.searchKey = btDict["searchKey"] as? String
bowtie.rating = btDict["rating"] as! Double
let colorDict = btDict["tintColor"] as! [String: Any]
bowtie.tintColor = UIColor.color(dict: colorDict)
let imageName = btDict["imageName"] as? String
let image = UIImage(named: imageName!)
bowtie.photoData = image?.pngData()
bowtie.lastWorn = btDict["lastWorn"] as? Date
let timesNumber = btDict["timesWorn"] as! NSNumber
bowtie.timesWorn = timesNumber.int32Value
bowtie.isFavorite = btDict["isFavorite"] as! Bool
bowtie.url = URL(string: btDict["url"] as! String)
}
try! managedContext.save()
}
3、更新数据
func update(rating: String?) {
guard let ratingString = rating,
let rating = Double(ratingString) else {
return
}
do {
currentBowTie.rating = rating
try managedContext.save()
populate(bowtie: currentBowTie)
} catch let error as NSError {
if error.domain == NSCocoaErrorDomain &&
(error.code == NSValidationNumberTooLargeError || error.code == NSValidationNumberTooSmallError) {
rate(rateButton)
} else {
print("Could not save \(error), \(error.userInfo)")
}
}
}
QQ:3365059189
SwiftUI技术交流QQ群:518696470
- 请关注我的专栏icloudend, SwiftUI教程与源码