简体   繁体   中英

Convert a NSInteger to NSString Xcode iOS8

I'm trying to convert an NSInteger to a NSString to show the NSInteger value in a UIAlerView. But the problem is that I get this error: "Bad receiver type 'NSInteger' (aka 'long')" when I'm trying to convert the NSInteger.

The NSInteger:

NSInteger clasesDadas = clases.count;

The clases.count is the number of rows I have in the TableView.

The code is:

-(void)infoAction
{
    NSInteger clasesDadas = clases.count;

    NSString *inStr = [NSString stringWithFormat:@"%d", [clasesDadas intValue]]; /*HERE IS THE ERROR*/

    UIAlertView *alertatiempo = [[UIAlertView alloc] initWithTitle:@"Información" message:inStr delegate:self cancelButtonTitle:@"Aceptar" otherButtonTitles:nil];
    [alertatiempo show];

}

Can anyone help me? Thank you very much.

intValue is not methods that exist on a NSInteger but on NSNumber . Since NSInteger is a typedef for a primitive type int on 32Bit and long on 64bit it does not have an methods.

Here is how you'd could do it, casting to make sure it works on both 32 and 64 bit devices.

NSString *inStr = [NSString stringWithFormat:@"%ld", (long)clasesDadas ]; 

Also as stated by meronix the count method will result in an NSUInteger so you might want to check the type and format accordingly

You can use with Boxed Expressions.

Eg @(10).stringValue or @(variable).stringValue

Your clasesDadas is already a NSInteger , so you cannot use the method intValue .

To convert your integer to string you can convert it in NSNumber and use the method stringValue like this :

NSString *inStr = [[NSNumber numberWithInteger:clasesDadas] stringValue]

You can also use the syntax @() to convert your NSInteger to object (NSNumber). For example :

NSString *inStr = [NSString stringWithFormat:@"%@", @(clasesDadas)];

try this:

NSString *inStr = [NSString stringWithFormat:@"%lu", (unsigned long)clasesDadas];

NSInteger declaration may differ on 32 or 64 bit devices, so this is the apple suggestion to get an array.count for a NSString

NSString *inStr = [NSString stringWithFormat:@"%d", clasesDadas];
NSString *inStr = [NSString stringWithFormat:@"%d", (int)clasesDadas];

这应该工作正常。

 NSString *inStr = [NSString stringWithFormat:@"%d", (int)clases.count]; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM