0
votes

I have this piece of code as shown below

func getItemsOnList(){

    let app = UIApplication.shared.delegate as! AppDelegate
    let context = app.persistentContainer.viewContext

    //fetchRequest to get the List
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "List")
    let predicate = NSPredicate(format: "title == %@", listName)
    fetchRequest.returnsObjectsAsFaults = false
    fetchRequest.predicate = predicate

    if let fetchResults = try? context.fetch(fetchRequest){
        if fetchResults.count > 0 {
            for listEntity in fetchResults {
                let list = listEntity as! List
                print(list.title as Any)
                itemsOnListSet = list.contains!

What this does is it gets the Items from the specified List using the .contains relationship between the two entities, and saves all the items in to an NSSet.

What i want to do is to populate a TableView with the objects that are in the NSSet.

Is there a function related to NSSet which allows me to get the items from the set? Or should i save the items in an Array instead of an NSSet.

P.S. the .contains relationship is of type NSSet

    @NSManaged public var contains: NSSet?
1
NSSet is Array without indexing, you dont use it as datasource tableview, it usually be used for searching/filtering, and it cant contains duplicate - Tj3n

1 Answers

2
votes

why don't you convert the Set to Array using,

if let _ = list.contains {
    let itemsOnListArray = list.contains!.allObjects 
}

else

if let unwrappedList = list.contains {
        let itemsOnListArray = unwrappedList.allObjects 
}

Now use your itemsOnListArray as your tableView's data source :)

EDIT:

Your code

let item = itemsOnListArray[indexPath.row] 
cell.textLabel?.text = item as? String

Assumes itemsOnListArray is a array of strings!!! Which is absolutely impossible because list.contains! is a set of NSManagedObjects or if you created mapped subclasses of ManagedObjects than it will contain a set of your managed objects like items.

What you should be doing is (because you have not provided the description of item am assuming item has a name property in it)

let item = itemsOnListArray[indexPath.row] as! Item
cell.textLabel?.text = item.name