I have an ordered txt file like this:
aaa
bbb
ccc
ddd
eee
I want to check if “ddd” string exists in the file…
Here my func:
- (BOOL) asd:(NSString*)sting
{
NSArray *LinesCount =
[[NSString stringWithContentsOfFile:@"longfile.txt"
encoding:NSStringEncodingConversionAllowLossy error:nil]
componentsSeparatedByString:@"\r\n"];
unsigned index = (unsigned)CFArrayBSearchValues(
(CFArrayRef)LinesCount,
CFRangeMake(0, CFArrayGetCount((CFArrayRef)LinesCount)),
(CFStringRef)string,
(CFComparatorFunction)CFStringCompare,
NULL);
if (index < [LinesCount count]) return YES;
return NO;
}
Why does it always returns NO, with any string?
The problem is in the way you read in the array.
If you replace the code that assigns
LineCountwithyou will see the binary search performs fine.
There are two issues in your code:
As an example:
yields (note the last empty element):