NSSet has no subscript members
Asked Answered
P

3

8

I have a CoreData object that has an relationship that is NSSet. I'm trying to use this as my dataSource, but getting the following

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = playerTableView.dequeueReusableCellWithIdentifier("Cell")! as UITableViewCell
    cell.textLabel?.text = self.game.players[indexPath.row]
    return cell
}

How do I use my NSSet in a tableView and I believe this would be unordered so potentially different each time, so how could I order this set?

Purree answered 9/10, 2016 at 15:39 Comment(3)
If you want to bring order to a set, then you should load the elements into an array.Aguila
@TimVermeulen Yes, i've started to look at this, it's second on my list. I guess I could order the CoreData objects by name into an array?Purree
For instance, yeah.Aguila
Q
13

You can use allObjects to get an array from the set and sort the objects afterwards.

let orderedPlayers = (game.players!.allObjects as! [Player]).sort { $0.name < $1.name }

If you declare the set as native Swift type Set<Player> – CoreData supports also Swift types – you can even omit the type cast and allObjects:

let orderedPlayers = game.players!.sort { $0.name < $1.name }
Quillen answered 9/10, 2016 at 18:55 Comment(2)
Hey @vadian, when I turned the Set<> how can I use the indexPath.row in cellForItemAt. It gives an error like "Cannot convert value of type 'Int' to expected argument type 'Set<Item>.Index"Nonconformity
A Set is unordered, better use an array as described in the answer.Quillen
P
0

This is how I did it:

for player in game.players! {
        orderedPlayers.append(player as! Player)
    }
    orderedPlayers.sortInPlace({ $0.name < $1.name })
Purree answered 9/10, 2016 at 18:49 Comment(0)
S
0

You can add subScript to game core data class like this:

subscript(index: Int) -> Player? {
    let descriptor = NSSortDescriptor(key: "name", ascending: true)
    let orderedPlayerArray = players?.sortedArray(using: [descriptor])
    let playerWhereIndex = orderedPlayerArray?[index]
    return playerWhereIndex as? Player
}
Stringendo answered 20/5, 2021 at 5:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.