如何在一个已排序的NSArray中搜索某一特定字符串?答案是使用CFArray自带的搜索功能

来源:互联网 发布:ipad淘宝hd如何横屏 编辑:程序博客网 时间:2024/05/16 11:40
 如何在一个已排序的NSArray中搜索某一特定字符串?答案是使用CFArray自带的搜索功能:

 

 
NSMutableArray *sortedArray = [NSMutableArray arrayWithObjects@"Alice"@"Beth"@"Carol",@"Ellen",nil];
 
//Where is "Beth"?
unsigned index = (unsigned)CFArrayBSearchValues((CFArrayRef)sortedArray,
                                                                                    CFRangeMake(0CFArrayGetCount((CFArrayRef)sortedArray)),
                                                                                    (CFStringRef)@"Beth",
                                                                                    (CFComparatorFunction)CFStringCompare,
                                                                                    NULL);
if (index < [sortedArray count])
{
         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"?
unsigned insertIndex = (unsigned)CFArrayBSearchValues((CFArrayRef)sortedArray,
                                                                                            CFRangeMake(0CFArrayGetCount((CFArrayRef)sortedArray)),
                                                                                            (CFStringRef)@"Debra",
                                                                                            (CFComparatorFunction)CFStringCompare,
                                                                                            NULL);
[sortedArray insertObject:@"Debra" atIndex:insertIndex];
NSLog([sortedArray description]);
原创粉丝点击