Swiftで遊ぼう! on Hatena

あしたさぬきblogでやってた初心者オヤジのiOSプログラミング奮闘記がHatenaに来ました

Swiftで遊ぼう! - 632 - Zoomania 2

データベースにシードするDataHelplerというクラスをコードしている途中でした。シードするメソッドを書いたので次は確認のコードを買います。コンソールにデーターベスの内容を表示するメソッドです。

public func printAllZoos() {
    let zooFetchRequest = NSFetchRequest(entityName: "Zoo")
    let primarySortDescriptor = 
     NSSortDescriptor(key: "name", ascending: true)
    zooFetchRequest.sortDescriptors = [primarySortDescriptor]
        
        
    let allZoos = 
     try! context.executeFetchRequest(zooFetchRequest) as! [Zoo]
        
    for zoo in allZoos {
     print("Zoo Name: \(zoo.name!)\n
              Location: \(zoo.location!) \n-------\n", 
                  terminator: "")
            
    }
}
    
public func printAllClassifications() {
    let classificationFetchRequest = 
     NSFetchRequest(entityName: "Classification")
    let primarySortDescriptor = 
     NSSortDescriptor(key: "family", ascending: true)
        
    classificationFetchRequest.sortDescriptors = 
         [primarySortDescriptor]
        
    let allClassifications = 
     try! context.executeFetchRequest(classificationFetchRequest)
         as! [Classification]
        
    for classification in allClassifications {
     print("Scientific Classification: 
        \(classification.scientificClassification!)\n
           Order: \(classification.order!)\n
             Family: \(classification.family!) \n-------\n",
               terminator: "")
    }
}
    
public func printAllAnimals() {
    let animalFetchRequest = NSFetchRequest(entityName: "Animal")
    let primarySortDescriptor = 
     NSSortDescriptor(key: "habitat", ascending: true)
        
    animalFetchRequest.sortDescriptors = [primarySortDescriptor]
        
    let allAnimals = 
     try! context.executeFetchRequest(animalFetchRequest)
        as! [Animal]
        
    for animal in allAnimals {
        print("\(animal.commonName!), 
          a member of the \(animal.classification!.family!) family, 
            lives in the \(animal.habitat!) at the following zoos:\n", 
              terminator: "")
        for zoo in animal.zoos! {
                print("> \(zoo.name!)\n", terminator: "")
        }
        print("-------\n", terminator: "")
    }
}

これでこのクラスのコードは全て終了です。じゃあどこで呼び出すのか? これは最初に説明しましたが、NSManagedObjectContextのインスタンスができるAppDelegateです。

今日はここまで。