IOS: error in HomeDirectory

2019-09-02 22:11发布

问题:

I have this code

NSString *nextSequentialFile =
    [filePath stringByReplacingOccurrencesOfString:photoNumber
    withString:[NSString stringWithFormat:@"%d", (index + 1)]
    options:NSBackwardsSearch
    range:[filePath rangeOfString:photoNumber options:NSBackwardsSearch]];

but I have this error and I don't understand beacuse it happens.

Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSCFString replaceOccurrencesOfString:withString:options:range:]: Range or index out of bounds'

回答1:

Try:

NSString *nextSequentialFile =
[filePath stringByReplacingOccurrencesOfString:photoNumber
withString:[NSString stringWithFormat:@"%d", (index + 1)]
options:NSBackwardsSearch
range:NSMakeRange(0, filePath.length)];


回答2:

It's likely that rangeOfString:photoNumber is out-of-range. I would recommend logging each of the values you pass to this method in order tell which is at fault.



回答3:

Never assume that methods like rangeOfString:options: return a valid range. From the docs:

Return Value

An NSRange structure giving the location and length in the receiver of the first occurrence of aString, modulo the options in mask. Returns {NSNotFound, 0} if aString is not found or is empty (@"").

[Emphasis added]

So obtain the range first and check for NSNotFound before attempting to use it.