IOS: error in HomeDirectory

自古美人都是妖i 提交于 2019-12-12 04:00:13

问题


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.



来源:https://stackoverflow.com/questions/7770135/ios-error-in-homedirectory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!