Txt 文件文本读取
Photoes.txt
Adirondack Blue
Adirondack Red
Agata
Agria
Ajanhuiri
Almond
Alpine Russet
Alturas
Amandine
Amflora
Andean black
Annabelle
Anuschka
Anya
Arran Victory
Atlantic
Atlas
Augusta
Austrian Crescent
Avalanche
Baccara
Bamberg
读取文本,并转化为对象:
import CoreData
extension NSPersistentContainer {
func importPotatoes() {
performBackgroundTask { context in
let request: NSFetchRequest<Potato> = Potato.fetchRequest()
do {
if try context.count(for: request) == 0 {
// Import some spuds
sleep(3)
guard let spudsURL = Bundle.main.url(forResource: "Potatoes", withExtension: "txt") else { return }
let spuds = try String(contentsOf: spudsURL)
let spudList = spuds.components(separatedBy: .newlines)
for spud in spudList {
let potato = Potato(context: context)
potato.variety = spud
potato.crowdRating = Float(arc4random_uniform(50)) / Float(10)
}
try context.save()
}
} catch {
print("Error importing potatoes: \(error.localizedDescription)")
}
}
}
}