简体   繁体   中英

Warning: Implicit conversion loses Integer precision in xcode 6

I know it could be a duplicate, but i got about 30 Implicit conversion loses Integer precision warnings in my ios project after updating xcode to version 6.

First Example:

NSArray * stations = [self stationsJSON][KEY_ITEM_LIST];

int newSize = (stations.count + 1); // Implicit conversion loses Integer precision: 'unsigned long' to 'int'

Second Example:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ...
    int index = indexPath.row / 2; // Implicit conversion loses Integer precision: 'long' to 'int'
    ...
}

I know what the warning means. Using NSInteger can help to avoid this warning.

I don't understand, why there was no warnings in xcode 5 ? And why there is no warning after i change the line

int index = indexPath.row / 2;

to

int index = indexPath.row / 2i;

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.

在此输入图像描述

NSArray count is NSUInteger .

NSIndexPath row is NSInteger .

On 64-bit systems, NSUInteger and NSInteger are 64-bits but int is 32-bit. So the value won't fit which results in the warning.

It's best to avoid int in iOS. Instead, use the same type as the values you are dealing with.

NSInteger index = indexPath.row / 2;

You probably see these in Xcode 6 due to the default warnings. You can easily see these in Xcode 5 with the right warning settings and building for 64-bit.

I was always annoyed by these warnings, so I came up with simple solution to avoid it:

@interface NSIndexPath(UnsignedIndex)

@property (nonatomic, readonly) NSUInteger sectionIndex;
@property (nonatomic, readonly) NSUInteger rowIndex;

@end

@implementation NSIndexPath(UnsignedIndex)

- (NSUInteger)sectionIndex {

    return (NSUInteger)self.section;
}

- (NSUInteger)rowIndex {

    return (NSUInteger)self.row;
}

@end

Simply use rowIndex and sectionIndex properties from this category instead of NSIndexPath's row and section properties.

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