将NSInteger转换为NSString [英] casting NSInteger into NSString

查看:243
本文介绍了将NSInteger转换为NSString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从几个不同的部分中制作一个字符串.这是我现在所拥有的.我的代码中没有任何错误,但是一旦我运行它并执行触发它的事件,我就会得到EXC_BAD_ACCESS.有没有其他方法可以将此NSInteger转换为NSString?

I'm trying to make one string out of several different parts. This below is what i have right now. I don't get any errors in my code but as soon as i run this and do the event that triggers it i get EXC_BAD_ACCESS. Is there another way of casting this NSInteger into a NSString?

NSString *part1, *part2, *tempString;

NSInteger num1;
NSInteger num2;

part1=@"some";
part2=@"text";    

tempString = [NSString stringWithFormat:@"%@%@%@%@", 
              part1,
              (NSString *)num1, 
              part2, 
              (NSString *)num2];

推荐答案

字符串和整数本质上是不同的数据类型,在这种情况下,在Objective-C中进行强制转换将不会为您进行转换,向编译器撒谎,说明发生了什么(因此可以编译),但在运行时会崩溃.

A string and an integer are fundamentally different data types, and casting in Objective-C won't do a conversion for you in this case, it'll just lie to the compiler about what's happening (so it compiles) but at runtime it blows up.

您可以使用%d而不是%@将整数直接嵌入格式字符串中:

You can embed an integer directly into a format string by using %d instead of %@:

    tempString = [NSString stringWithFormat:@"%@%d%@%d", part1,num1, part2, num2];


NSInteger只是常规"int"(数字)的奇特名称. NSString是对字符串对象的对象引用.某些数字类型(int和浮点数)可以像这样直接在C语言中相互转换,但是这两种类型根本不能互操作.听起来您可能来自更宽容的语言? :)


NSInteger is just a fancy name for a regular "int" (number). An NSString is an object reference to a string object. Some numeric types (int and floating point) can be sort of converted between eachother directly in C like this, but these two aren't inter-operable at all. It sounds like you might be coming from a more permissive language? :)

这篇关于将NSInteger转换为NSString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆