con*_*fin 26 iphone cocoa-touch objective-c nsarray 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]);
Run Code Online (Sandbox Code Playgroud)
OUTPUT:
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
Run Code Online (Sandbox Code Playgroud)
使用上面的代码,telephoneArray可以有1到5之间的计数,但phoneSet总是有一个值1.我假设有一个明显的错误,但我看不到在哪里.
ind*_*gie 94
这不正确:
NSSet *telephoneSet = [[NSSet alloc] init];
[telephoneSet setByAddingObjectsFromArray:telephoneArray];
Run Code Online (Sandbox Code Playgroud)
该方法返回一个你不做任何事情的NSSet(它不会将对象添加到telephoneSet,它会创建一个新的NSSet).改为:
NSSet *telephoneSet = [NSSet setWithArray:telephoneArray]
另请注意,与数组不同,集合不能包含重复项.因此,如果您的数组中有重复的对象并将它们放在一个集合中,则会删除重复项,这会影响对象计数.
Anu*_*rag 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];
}
Run Code Online (Sandbox Code Playgroud)
此外,就像PCWiz所说,你不需要NSSet在你的情况下分配一个新对象.只需调用类方法即可setWithArray:.
NSSet *telephoneSet = [NSSet setWithArray:telephoneArray]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
41950 次 |
| 最近记录: |