Jonnny
Jonnny

Reputation: 5039

NSSet has no subscript members

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?

Upvotes: 8

Views: 2632

Answers (3)

Saeed All Gharaee
Saeed All Gharaee

Reputation: 1683

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
}

Upvotes: 0

vadian
vadian

Reputation: 285059

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 }

Upvotes: 13

Jonnny
Jonnny

Reputation: 5039

This is how I did it:

for player in game.players! {
        orderedPlayers.append(player as! Player)
    }
    orderedPlayers.sortInPlace({ $0.name < $1.name })

Upvotes: 0

Related Questions