如何在一个已排序的NSArray中搜索某一特定字符串?答案是使用CFArray自带的搜索功能:
NSMutableArray *sortedArray = [NSMutableArrayarrayWithObjects:@"Alice",@"Beth",@"Carol",@"Ellen",nil];
//Where is "Beth"?
unsignedindex = (unsigned)CFArrayBSearchValues((CFArrayRef)sortedArray,
CFRangeMake(0,CFArrayGetCount((CFArrayRef)sortedArray)),
(CFStringRef)@"Beth",
(CFComparatorFunction)CFStringCompare,
NULL);
if(index < [sortedArraycount])
{
NSLog(@"Beth was found at index %u", index);
}else{
NSLog(@"Beth was not found (index is beyond the bounds of sortedArray)");
}
//Where should we insert "Debra"?
unsignedinsertIndex = (unsigned)CFArrayBSearchValues((CFArrayRef)sortedArray,
CFRangeMake(0,CFArrayGetCount((CFArrayRef)sortedArray)),
(CFStringRef)@"Debra",
(CFComparatorFunction)CFStringCompare,
NULL);
[sortedArrayinsertObject:@"Debra"atIndex:insertIndex];
NSLog([sortedArraydescription]);
NSMutableArray *sortedArray = [NSMutableArrayarrayWithObjects:@"Alice",@"Beth",@"Carol",@"Ellen",nil];
//Where is "Beth"?
unsignedindex = (unsigned)CFArrayBSearchValues((CFArrayRef)sortedArray,
CFRangeMake(0,CFArrayGetCount((CFArrayRef)sortedArray)),
(CFStringRef)@"Beth",
(CFComparatorFunction)CFStringCompare,
NULL);
if(index < [sortedArraycount])
{
NSLog(@"Beth was found at index %u", index);
}else{
NSLog(@"Beth was not found (index is beyond the bounds of sortedArray)");
}
//Where should we insert "Debra"?
unsignedinsertIndex = (unsigned)CFArrayBSearchValues((CFArrayRef)sortedArray,
CFRangeMake(0,CFArrayGetCount((CFArrayRef)sortedArray)),
(CFStringRef)@"Debra",
(CFComparatorFunction)CFStringCompare,
NULL);
[sortedArrayinsertObject:@"Debra"atIndex:insertIndex];
NSLog([sortedArraydescription]);