Warning "Implicit conversion loses integer precision..."

janeh picture janeh · Jan 11, 2012 · Viewed 18.1k times · Source

I am doing a shopping cart tutorial: I have an array that collects input from a text field, and then displays it in the NSTableView. You can check an item, and remove it from the list. I want to display a warning only if something is checked. So, I have this:

    -(IBAction)removeItemFromShoppingList:(id)sender {
        int selectedItemIndex = [shoppingListTableView selectedRow];
        if (selectedItemIndex == -1) return;
        NSAlert *alert = [[NSAlert alloc] init];
        ...
        [alert runModal];
        [alert release];
}

On line 2 here (int selectedItemIndex...) I get a yellow warning: Implicit conversion loses integer precision:’NSInteger’ (aka ‘long’) to ‘int’.

Why?

Answer

Fang Jiaan picture Fang Jiaan · Jan 26, 2012

From apple's documentation:

When building 32-bit applications, NSInteger is a 32-bit integer. A 64-bit application treats NSInteger as a 64-bit integer.

#if __LP64__ || TARGET_OS_EMBEDDED || TARGET_OS_IPHONE || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64
typedef long NSInteger;
#else
typedef int NSInteger;
#endif

UPDATE:

Explain in detail:

[shoppingListTableView selectedRow] returns a NSInteger, and you are building an 64-bit application, so it is in fact a long.

You can use long selectedItemIndex instead of int selectedItemIndex to suppress this warning, but the warning appears again when building 32-bit version.

A better way is using NSInteger selectedItemIndex, which handles this case correctly.