ios - 将 charAtIndex 分配给 stringWithCharacters 会给出无效的转换警告和错误的访问错误

标签 ios objective-c nsmutablestring

我正在尝试从名字+姓氏中获取名字和姓氏。

int loop=0;
NSMutableString *firstname = [[NSMutableString alloc]init];
 NSMutableString *fullName = [[NSMutableString alloc]initWithString:@"Anahita+Havewala"];

for (loop = 0; ([fullName characterAtIndex:loop]!='+'); loop++) {
    [firstname appendString:[NSString stringWithCharacters:(const unichar *)[fullName characterAtIndex:loop] length:1]];
}
NSLog(@"%@",firstname);

我尝试从 unichar 类型转换为 const unichar*,因为 characterAtIndex 返回一个 unichar 而 stringWithCharacters 接受一个 const unichar。

当遇到此行时,这会导致从较小的整数类型警告转换为应用程序崩溃(访问错误)。

为什么 Objective C 中的字符串操作如此复杂?

最佳答案

您可以使用 componentsSeparatedByString: 轻松获取名字和姓氏方法。

NSMutableString *fullName = [[NSMutableString alloc]initWithString:@"Anahita+Havewala"];
NSArray *components = [fullName componentsSeparatedByString:@"+"];
NSString *firstName = components[0];
NSString *lastName  = components[1];

注意:您需要进行适当的数组边界检查。您也可以使用 NSScanner出于同样的目的。

关于ios - 将 charAtIndex 分配给 stringWithCharacters 会给出无效的转换警告和错误的访问错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33140379/

相关文章:

ios - 在 Swift dequeueReusableCellWithIdentifier 中,需要时间来加载

ios - 旋转后如何调整相机纵横比?

objective-c - xcode文件打开原生C

objective-c - 如何将数据写入xml文件

objective-c - objective-c : convert a NSMutableString in NSString

objective-c - 如何向已存在的字符串添加字符?

objective-c - IOS 和 shoutcast

ios - 显示 UIAlertView 后执行操作?

objective-c - 在没有导航 Controller 的情况下关闭多个模态视图

objective-c - 使用 NSMutableString 追加到文件末尾