初始化 NSString 时的 EXC_BAD_ACCESS
我想用长度为 1 的字符初始化 NSString
,但出现错误。这是我的代码:
for(int i=0;i<[word length];i++)
{
letterMap = [self stringToAscii:[word substringWithRange:NSMakeRange(i, 1) ]];
NSInteger codec = (letterMap + shifter) % 26;
unichar ch = [self asciiToString:codec];
NSString * codedLetter = [NSString stringWithCharacters:ch length:[ch length]];
}
I want to initialise an NSString
with a character with length of 1, but I get an error. Here's my code:
for(int i=0;i<[word length];i++)
{
letterMap = [self stringToAscii:[word substringWithRange:NSMakeRange(i, 1) ]];
NSInteger codec = (letterMap + shifter) % 26;
unichar ch = [self asciiToString:codec];
NSString * codedLetter = [NSString stringWithCharacters:ch length:[ch length]];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
unichar
不是 ObjC 对象,它是单个 unicode 字符的原始 C 类型(或 typedef)。您需要像这样调用 NSString 方法(它可以在类似 C 的数组中接受多个字符):(您的代码行有两个问题:首先,您传递的是
unichar
unichar 的值code> 作为第一个参数,而不是指向它的指针,第二个参数是您尝试在不是 ObjC 对象的对象上调用-length
,甚至是指针它会因它而爆炸。后者当它试图向某些人发送消息时随机内存地址。)unichar
isn't an ObjC object, it's a primitive C type (or typedef) for a single unicode character. You need to call the NSString method (which can take multiple characters in a C-like array) like this:(There are two problems in your line of code: first that you're passing the value of a
unichar
as the first argument, instead of a pointer to it, and the second that you're trying to call-length
on something that's not an ObjC object, or even a pointer. It's blowing up due the latter when it tries to send a message to some random memory address.)