NSString ReplaceCharactersInRange 崩溃
我有以下代码:
-(void) swapCharacters: (NSMutableString *) set : (NSInteger) first : (NSInteger) second {
NSLog(@"swap: set = '%@', first = '%d', second = '%d'", set, first, second);
NSRange rangeSecond = NSMakeRange((NSUInteger) second, 1);
NSRange rangeFirst = NSMakeRange((NSUInteger) first, 1);
[set replaceCharactersInRange:rangeSecond withString:[set substringWithRange:rangeFirst]];
}
NSLog 打印为:set = 'happy', first = '0', secondary = '0' 但程序在 [set rangeFirst = ....] 处崩溃,没有任何调试信息。
感谢您的任何帮助。
I have the following code:
-(void) swapCharacters: (NSMutableString *) set : (NSInteger) first : (NSInteger) second {
NSLog(@"swap: set = '%@', first = '%d', second = '%d'", set, first, second);
NSRange rangeSecond = NSMakeRange((NSUInteger) second, 1);
NSRange rangeFirst = NSMakeRange((NSUInteger) first, 1);
[set replaceCharactersInRange:rangeSecond withString:[set substringWithRange:rangeFirst]];
}
NSLog print is : set = 'happy', first = '0', second = '0'
But the program crashes at [set rangeFirst = ...........] without any debug info.
Thanks for any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我发现您的代码中应该更改一些内容。这是我为使您的交换功能发挥作用所做的工作。
这是函数:
这是函数的调用方式:
这是输出:
*注意,对于 Objective-C 中的函数,名称就像描述
*我没有使用 NSInteger,而是使用普通 int,因为 NSInteger 不是这里必需
*当使用 NSLog 或字符串格式时,%@ 用于对象(NSString,NSInteger...),%i 用于 int , %f 代表 float,%d 代表 double
我希望有所帮助,编码愉快!
I found a few things that should be changed in your code. Here is what I did to make your swap function work.
This is the function:
This is how the function was called:
This is the output:
*Notice that with functions in objective-c, the name is like a description
*Instead of using NSInteger, I used a normal int because an NSInteger is not necessary here
*When using NSLog or string formatting, %@ is for objects (NSString,NSInteger...), %i is for int, %f is for float and %d is for double
I hope that helped, happy coding!
我只是尝试你的代码,它像这样为我工作
,我这样称呼它
,这是我得到的 NSLog :
您在调用该方法时是否将 NSMutableString 或 NSString 传递给该方法?
传递 NSString 这是我能够使代码崩溃的唯一方法。
I just try your code and it's working for me like this
And I'm calling it like this
And this is the NSLog I get :
Are you passing a NSMutableString or a NSString to that method when you are calling it?
Passing a NSString it's the only way I'm able to make that code crash.