我有一些NSDictionary
个对象存储在名为NSArray
的{{1}}中。我获取键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]);
使用上面的代码,telephoneArray可以有1到5之间的计数,但phoneSet总是有一个值1.我假设有一个明显的错误,但我看不到在哪里。
答案 0 :(得分:93)
这是不正确的:
NSSet *telephoneSet = [[NSSet alloc] init];
[telephoneSet setByAddingObjectsFromArray:telephoneArray];
该方法返回一个你不做任何事情的NSSet(它不会将对象添加到telephoneSet,它会创建一个新的NSSet)。这样做:
NSSet *telephoneSet = [NSSet setWithArray:telephoneArray]
另外,请注意,与数组不同,集合不能包含重复项。因此,如果您在数组中有重复的对象并将它们放在一个集合中,那么将删除重复项,这会影响对象的数量。
答案 1 :(得分:11)
最初telephoneArray
包含对n
个不同对象的引用。循环结束后,它确实包含n
个引用,但每个引用都指向同一个newTelephone
对象。
数组可以包含重复项,因此无关紧要。一个集合不能有重复,你的整个telephoneArray基本上由一个单独的对象组成,所以你只看到一个。
在你的循环中,你必须创建一个新对象或从某个地方获取电话对象:
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]
答案 2 :(得分:2)
您可以使用以下命令从数组创建新的NSSet:
let mySet = NSSet(array : myArray)
此外,您可以使用。
将数组中的对象添加到已存在的NSMutableSet中myMutableSet = myMutableSet.addingObjects(from: myArray)