Rebuild an NSArray by grouping objects that have matching id numbers?

前端 未结 5 1320
醉酒成梦
醉酒成梦 2020-11-29 06:38

I have an NSArray and each object in the array has a groupId and a name. Each object is unique but there are many with the same groupId. Is there a way i can tear the arra

5条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 07:26

    Swift implementation of Sergery's answer for my fellow noobs.

    class People: NSObject {
        var groupId: String
        var name : String
        init(groupId: String, name: String){
            self.groupId = groupId
            self.name = name
        }
    }
    
    
    let matt = People(groupId: "1", name: "matt")
    let john = People(groupId: "2", name: "john")
    let steve = People(groupId: "3", name: "steve")
    let alice = People(groupId: "4", name: "alice")
    let bill = People(groupId: "1", name: "bill")
    let bob = People(groupId: "2", name: "bob")
    let jack = People(groupId: "3", name: "jack")
    let dan = People(groupId: "4", name: "dan")
    let kevin = People(groupId: "1", name: "kevin")
    let mike = People(groupId: "2", name: "mike")
    let daniel = People(groupId: "3", name: "daniel")
    
    let arrayOfPeople = NSArray(objects: matt, john, steve, alice, bill, bob, jack, dan, kevin, mike, daniel)
    
    var resultArray = NSMutableArray()
    let groups = arrayOfPeople.valueForKeyPath("@distinctUnionOfObjects.groupId") as [String]
    
    
    for groupId in groups {
        var entry = NSMutableDictionary()
        entry.setObject(groupId, forKey: "groupId")
        let predicate = NSPredicate(format: "groupId = %@", argumentArray: [groupId])
        var groupNames = arrayOfPeople.filteredArrayUsingPredicate(predicate)
        for i in 0..

    Note the @ sign in valueForKeyPath. that tripped me up a little :)

提交回复
热议问题