wag*_*shi 1 objective-c nsmutablearray setvalue
我的代码:
NSArray *array = //objects here
NSMutableArray *mutarray = [[NSMutableArray alloc] init];
for (NSString *s in array)
{
NSRange ran = [s rangeOfString:@"abc"];
if (ran.location != NSNotFound)
{
int inde = [array indexOfObject:s];
[mutarray setValue:[NSNumber numberWithInt:inde] forKey:s];
}
}
NSLog (@"mutarray: %@", mutarray);
Run Code Online (Sandbox Code Playgroud)
我尝试过NSMutableDictionary,但内容是无序的,所以我更喜欢NSMutableArray有序地存储值和键.但NSLog的输出什么也没有显示,到底是什么?NSMutableDictionary的输出显示了四个发现.
编辑:
我甚至在NSLog前面尝试过这段代码,但没有显示:
[mutarray setValue:@"aha" forKey:@"jaha"];
Run Code Online (Sandbox Code Playgroud)
编辑:伙计们,谢谢你的回答!现在我明白了.但问题是我将数字存储为值和字符串作为键.我有一个无序的NSMutableDictionary.我还没弄明白我应该怎么订购它.我有我使用的代码,但没有正确编写:
NSInteger intSort(id num1, id num2, void *context)
{
int v1 = [num1 intValue];
int v2 = [num2 intValue];
if (v1 < v2)
return NSOrderedAscending;
else if (v1 > v2)
return NSOrderedDescending;
else
return NSOrderedSame;
}
Run Code Online (Sandbox Code Playgroud)
在其他方法:
NSArray *ordered = [[mutdic allValues] sortedArrayUsingFunction:intSort context:NULL];
NSLog (@" ordered: %@", ordered);
Run Code Online (Sandbox Code Playgroud)
输出仅显示:
2011-08-29 22:36:03.998 scanner2[32359:207] ordered: (
1,
5,
9,
16
)
Run Code Online (Sandbox Code Playgroud)
输出应按数字顺序显示:
2011-08-29 22:36:03.992 scanner2[32359:207] mutdic: 5 jam (geologi) en
2011-08-29 22:36:03.993 scanner2[32359:207] mutdic: 9 jax. (geologi)jammen
2011-08-29 22:36:03.994 scanner2[32359:207] mutdic: 1 beta (geologi).
2011-08-29 22:36:03.995 scanner2[32359:207] mutdic: 16 .(geologi),be;ta;
Run Code Online (Sandbox Code Playgroud)
NSMutableArray不存储键/值对,它只存储对象.要将对象添加到数组,请使用该-addObject:方法.
使用数组存储有序的对象列表.在需要查找给定键的对象时使用字典.如果您想要字典键的有序列表,请使用
NSArray* orderedKeys =
[[myDictionary allKeys] sortedArrayUsingSelector:@selector(compare:)];
Run Code Online (Sandbox Code Playgroud)
编辑:还有几个选项.
只需存储索引数组,然后在主array字符串中查找值.
for (NSUInteger i = 0; i < [array count]; ++i)
{
NSString* s = [array objectAtIndex:i];
NSRange ran = [s rangeOfString:@"abc"];
if (ran.location != NSNotFound)
{
[mutarray addObject:[NSNumber numberWithInt:i]];
}
}
for (NSNumber* index in mutarray)
{
NSLog(@"Found %@:%@", index, [array objectAtIndex:[index intValue]]);
}
Run Code Online (Sandbox Code Playgroud)存储索引和字符串的二维数组:
for (NSUInteger i = 0; i < [array count]; ++i)
{
NSString* s = [array objectAtIndex:i];
NSRange ran = [s rangeOfString:@"abc"];
if (ran.location != NSNotFound)
{
[mutarray addObject:
[NSArray arrayWithObjects:[NSNumber numberWithInt:i],
s,
nil]];
}
}
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
7477 次 |
| 最近记录: |