繁体   English   中英

如何将 NSArray 中的对象放入 NSSet?

[英]How do I put objects in an NSArray into an NSSet?

我有一些NSDictionary存储在一个对象NSArray称为telephoneArray 我获取键number的值,然后用数组中相同索引处的新对象替换我刚刚读取的NSDictionary 然后我想将这些新对象放入NSSet 如何做到这一点? 请参阅下面我的失败尝试。

    // Add all telephones to this branch
    for (int i=0; i<[telephoneArray count]; i++) {

        [newTelephone setBranch:newBranch];
        [newTelephone setNumber:[[telephoneArray objectAtIndex:i] valueForKey:@"number"]];

        NSLog(@"%@",[[telephoneArray objectAtIndex:i] valueForKey:@"number"]);
        [telephoneArray replaceObjectAtIndex:i withObject:newTelephone];
        NSLog(@"phone number %i = %@",i,[[telephoneArray objectAtIndex:i] valueForKey:@"number"]);

    }

    NSSet *telephoneSet = [NSSet setWithArray:telephoneArray];

    NSLog(@"telephoneArray=%i",[telephoneArray count]);
    NSLog(@"telephoneSet=%i",[[telephoneSet allObjects] count]);

输出:

2010-03-06 03:06:02.824 AIB[5160:6507] 063 81207
2010-03-06 03:06:02.824 AIB[5160:6507] phone number 0 = 063 81207
2010-03-06 03:06:02.825 AIB[5160:6507] 063 81624
2010-03-06 03:06:02.825 AIB[5160:6507] phone number 1 = 063 81624
2010-03-06 03:06:02.825 AIB[5160:6507] 063 81714
2010-03-06 03:06:02.826 AIB[5160:6507] phone number 2 = 063 81714
2010-03-06 03:06:02.826 AIB[5160:6507] 063 81715
2010-03-06 03:06:02.826 AIB[5160:6507] phone number 3 = 063 81715
2010-03-06 03:06:02.826 AIB[5160:6507] telephoneArray=4
2010-03-06 03:06:02.827 AIB[5160:6507] telephoneSet=1

使用上面的代码,telephoneArray 的计数可以在 1 到 5 之间,但 phoneSet 的值始终为 1。我认为有一个明显的错误,但我看不出在哪里。

这是不正确的:

NSSet *telephoneSet = [[NSSet alloc] init];
[telephoneSet setByAddingObjectsFromArray:telephoneArray];

该方法返回一个 NSSet,您没有对其进行任何操作(它不会将对象添加到 phoneSet,而是创建一个新的 NSSet)。 改为这样做:

NSSet *telephoneSet = [NSSet setWithArray:telephoneArray]

另请注意,与数组不同,集合不能包含重复项。 因此,如果您的数组中有重复的对象并将它们放入一个集合中,则将删除重复项,这会影响对象计数。

最初telephoneArray包含对n不同对象的引用。 循环结束后,它确实包含n引用,但每个引用都指向同一个newTelephone对象。

数组可以包含重复项,所以没关系。 Set 不能有重复项,并且您的整个 phoneArray 基本上由单个对象组成,因此您只会看到一个。

在您的循环中,您必须创建一个新对象或从某处获取电话对象:

for (int i=0; i<[telephoneArray count]; i++) {
    // Create the new object first, or get it from somewhere.
    Telephone *newTelephone = [[Telephone alloc] init];
    [newTelephone setBranch:newBranch];
    [newTelephone setNumber:[[telephoneArray objectAtIndex:i] valueForKey:@"number"]];
    [telephoneArray replaceObjectAtIndex:i withObject:newTelephone];
    // the array holds a reference, so you could let go of newTelephone
    [newTelephone release];
}

另外,就像 PCWiz 所说的,你不需要在你的情况下分配一个新的NSSet对象。 只需调用类方法setWithArray:

NSSet *telephoneSet = [NSSet setWithArray:telephoneArray]

斯威夫特 3 版本

您可以使用以下命令从数组创建新的 NSSet:

let mySet = NSSet(array : myArray)

此外,您可以将对象从数组添加到已经存在的 NSMutableSet 中。

myMutableSet =  myMutableSet.addingObjects(from: myArray)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM