user12655184
user12655184

Reputation:

fetch single core data elements and combine into single array

My swift code below saves 3 names to core data. Then in func joke it fetches the data and converts it to a array.The problem is in the debug area instead of listing the 3 names like [kim, Hailey,jessica]. It lists them on each line so they are not grouped in one array. So I want all 3 names in some like [name1,name2,name3].

    import UIKit
import CoreData

class ViewController: UIViewController,UITextFieldDelegate {
@IBOutlet var labelName : UILabel!
@IBOutlet var enterT : UITextField!

let appDelegate = UIApplication.shared.delegate as! AppDelegate //Singlton instance
var context:NSManagedObjectContext!

override func viewDidLoad() {
    super.viewDidLoad()

    openDatabse()
    joke()

}
func joke() {

    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")

 do {
    let results = try context.fetch(fetchRequest)
     let  Locations = results as! [Users]

     for location in Locations {
        print("Array: ",location.username)


     }
    } catch let error as NSError {
       print("Could not fetch \(error) ")
 }

}

func openDatabse()
{
    context = appDelegate.persistentContainer.viewContext
    let entity = NSEntityDescription.entity(forEntityName: "Users", in: context)
    let newUser = NSManagedObject(entity: entity!, insertInto: context)
    let newUser2 = NSManagedObject(entity: entity!, insertInto: context)
    let newUser3 = NSManagedObject(entity: entity!, insertInto: context)
    saveData(UserDBObj: newUser, UserDBObj2: newUser2, UserDBObj3: newUser3)

}

func saveData(UserDBObj:NSManagedObject,UserDBObj2:NSManagedObject,UserDBObj3:NSManagedObject)
{
    UserDBObj.setValue("kim kardashian", forKey: "username")
    UserDBObj2.setValue("jessica biel", forKey: "username")
    UserDBObj3.setValue("Hailey Rienhart", forKey: "username")




    print("Storing Data..")
    do {
        try context.save()
    } catch {
        print("Storing data Failed")
    }

    fetchData()
}

func fetchData()
{
    print("Fetching Data..")
    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
    request.returnsObjectsAsFaults = false
    do {
        let result = try context.fetch(request)
        for data in result as! [NSManagedObject] {
            let userName = data.value(forKey: "username") as! String

            print("User Name is : "+userName)
        }
    } catch {
        print("Fetching data Failed")
    }
}}

Upvotes: 0

Views: 895

Answers (3)

vadian
vadian

Reputation: 285039

First of all use a specific fetch request to get Users records.

If you want an array of strings ([String]) map the records to their user names

func joke() {
    let fetchRequest = NSFetchRequest<Users>(entityName: "Users")
    do {
        let result = try context.fetch(fetchRequest)
        let nameArray = result.map{$0.username}
        print(nameArray)
    } catch {
       print("Could not fetch \(error) ")
    }
}

But if you want a single string comma separated join the array

let nameString = result.map{$0.username}.joined(separator: ", ")
print(nameString)

Upvotes: 1

Truptika
Truptika

Reputation: 41

After fetching data, take one array of string and append your username in this array. For reference see below code

var nameArray = [String]()
for location in Locations {
         print("Array: ",location.username)
         nameArray.append(location.username)  
     }

Upvotes: 0

Vasucd
Vasucd

Reputation: 357

While fetching data from CoreData convert your managed object into your model class array .

Attaching code for your reference.

   do{
        if let userData = try managedContext?.fetch(fetchRequest) as? [Users]{
               // use this userData for your result and update ui accordingly    
       }

    }catch let error as NSError {
         print("Could not fetch. \(error), \(error.userInfo)")
    }

Upvotes: 0

Related Questions