问题
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?
回答1:
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.
回答2:
Because your variable is of type int
and you are trying to copy the value of a variable of type NSInteger
into it. An NSInteger
can hold larger values than an int
can, so you get a warning that overflow is possible. Probably the simplest fix is to change int
to NSInteger
. (When you want to copy the value of a variable to run tests on it, you should usually use a variable of the same type.)
回答3:
Use
int selectedItemIndex = (int)[shoppingListTableView selectedRow];
Instead of
int selectedItemIndex = [shoppingListTableView selectedRow];
回答4:
The selectedRow: method returns a value of type NSInteger.
You should make your selectedItemIndex of type NSInteger.
Please refer to:
http://developer.apple.com/library/mac/ipad/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSTableView_Class/Reference/Reference.html
回答5:
Use
NSInteger selectedItemIndex = [shoppingListTableView selectedRow];
Instead of
int selectedItemIndex = [shoppingListTableView selectedRow];
回答6:
You can update project settings, to remove all
Implicit conversion loses integer precision
warnings, by setting
Implicit Conversion to 32 Bit Type
to No
in project's build settings.

回答7:
I get out warning just do:
int selectedItemIndex = (int)[shoppingListTableView selectedRow];
来源:https://stackoverflow.com/questions/8813799/warning-implicit-conversion-loses-integer-precision