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

标签 iphone objective-c cocoa-touch nsarray nsset

我有一些 NSDictionary 对象存储在名为 telephoneArrayNSArray 中。我获取键 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 之间,但 telephoneSet 的值始终为 1。我认为有一个明显的错误,但我看不出在哪里。

最佳答案

这是不正确的:

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

该方法返回一个您什么都不做的 NSSet(它不会将对象添加到 telephoneSet,它会创建一个新的 NSSet)。改为这样做:

NSSet *telephoneSet = [NSSet setWithArray:telephoneArray]

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

关于iphone - 如何将 NSArray 中的对象放入 NSSet 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2391162/

相关文章:

javascript - 我可以在 Sencha Touch 中使用 Ext.JS 的 API 吗?

iphone - ios如何检查除法余数是否为整数

objective-c - CAOpenGLLayer 已裁剪图像

objective-c - NSUserDefault 在 NSMenuItem 绑定(bind)中注册的默认初始显示

iphone - iOS - 使用 ImageShack JSON API 上传图片

iphone - 添加自定义图像以在 iPhone 中启动应用程序?

iphone - UIImageView 背景图片和旋转帮助

objective-c - 如何在 Objective C 中使用 ARC 在类中声明指针成员变量?

ios - UICollectionView 在单元格之间画线

iphone - 查找私有(private) API 调用 _terminateWithStatus