My codes:
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);
I have tried NSMutableDictionary, but the content is unordered, so I prefer NSMutableArray to store Values and Keys orderly. But the output of NSLog showed nothing, what in the hell? The output of NSMutableDictionary showed four discoveries.
EDIT:
I even tried this code in front of the NSLog, but nothing shows:
[mutarray setValue:@"aha" forKey:@"jaha"];
EDIT: Guys, thanks for the answer! Now I understand. But the problem is that I store numbers as values and strings as keys. I have an NSMutableDictionary which is unordered. I still havent figured out how I should order it. I have the codes which I use, but it is not properly written:
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;
}
In other method:
NSArray *ordered = [[mutdic allValues] sortedArrayUsingFunction:intSort context:NULL];
NSLog (@" ordered: %@", ordered);
The output shows only:
2011-08-29 22:36:03.998 scanner2[32359:207] ordered: (
1,
5,
9,
16
)
The output should show this in ordered numerically:
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;
NSMutableArray
does not store key/value pairs, it only stores objects. To add an object to the array, use the -addObject:
method.
Use an array to store an ordered list of objects. Use a dictionary when you need to look up an object given some key. If you want an ordered list of a dictionary's keys, use
NSArray* orderedKeys =
[[myDictionary allKeys] sortedArrayUsingSelector:@selector(compare:)];
Edit: A couple of more options.
Just store an array of indexes, then look up the value in your main array
of strings.
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]]);
}
Store a two-dimensional array of indexes and strings:
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]];
}
}