将特定对象从数组保存到新数组中

时间:2015-04-30 09:55:35

标签: ios arrays swift

我有一个名为teamArray的数组,其中包含一个带有id,name和shortname的teamObject。这些名称循环并填充在tableView中。可以选择所有这些单元格,当选择单元格时,将indexPath插入到cellSelected数组中。我想将teamArray中选定的单元格id保存到一个新数组中。所以我想我需要将cellSelected数组indexPath与teamArray进行比较?我怎么能这样做?

阵列

var teamArray = Array<Team>()
var cellSelected = NSMutableArray()

didSelectRowAtIndexPath方法

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    tableView.deselectRowAtIndexPath(indexPath, animated: true)

    if (self.cellSelected.containsObject(indexPath)) {
        self.cellSelected.removeObject(indexPath)
    } else {
        self.cellSelected.addObject(indexPath)


    }

    tableView.reloadData()
}

teamObject

class Team: NSObject{
    var id: Int!
    var name: NSString!
    var shortname: NSString!

    init(id: Int, name:NSString, shortname: NSString) {
        self.id = id
        self.name = name
        self.shortname = shortname
    }
}

2 个答案:

答案 0 :(得分:2)

var teamSelected = [Team]()

didSelectRowAtIndexPath函数中:

let team = self.teamArray[indexPath.row] as Team
var removed = false

for (index, value) in enumerate(self.teamSelected) {
    if (value == team) {
        self.teamSelected.removeAtIndex(index)
        removed = true
    }
}

if (!removed) {
    self.teamSelected.append(team)
}

在您的cellForRowAtIndexPath函数中:

let team = self.teamArray[indexPath.row] as Team
var removed = false

for (index, value) in enumerate(self.teamSelected) {
    if (value == team) {    
        cell.accessoryView = cell.accessoryCheck
        removed = true
    }
}

if (!removed) {
    cell.accessoryView = cell.accessoryUncheck
}

当您想要访问所选teamSelected的ID时,您可以循环浏览Team

编辑:将cellSelected的名称更改为teamSelected

答案 1 :(得分:0)

您的主teamArray,已加载TableView

var teamArray = ["Kirit Modi","Kirit Modi 1","Kirit Modi 2","Kirit Modi 3","Kirit Modi 4","Kirit Modi 5","Kirit Modi 6","Kirit Modi 7","Kirit Modi 8","Kirit Modi 9"]

cellSelected

var cellSelected = : [String] = []

TableView委托didSelectRowAtIndexPath

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {

        if contains(cellSelected, Name[indexPath.row])
        {
            cellSelected.removeObject(Name[indexPath.row])
        }
        else{
            cellSelected.append(Name[indexPath.row])
        }
    }

使用以下函数从Array中删除对象。

extension Array {
    mutating func removeObject<U: Equatable>(object: U) {
        var index: Int?
        for (idx, objectToCompare) in enumerate(self) {
            if let to = objectToCompare as? U {
                if object == to {
                    index = idx
                }
            }
        }

        if(index != nil) {
            self.removeAtIndex(index!)
        }
    }
}