IOS: error in HomeDirectory

2019-09-02 22:24发布

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'

3条回答
太酷不给撩
2楼-- · 2019-09-02 22:34

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楼-- · 2019-09-02 22:36

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.

查看更多
走好不送
4楼-- · 2019-09-02 22:40

Try:

NSString *nextSequentialFile =
[filePath stringByReplacingOccurrencesOfString:photoNumber
withString:[NSString stringWithFormat:@"%d", (index + 1)]
options:NSBackwardsSearch
range:NSMakeRange(0, filePath.length)];
查看更多
登录 后发表回答