Search code examples
objective-ciosnsstringstring-formattingnsinteger

casting NSInteger into 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];

Solution

  • 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.

    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 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? :)