Chandler Buck
Chandler Buck

Reputation: 213

Implicit conversion loses integer precision: 'unsigned long' to 'int' (causes app to crash)

I am working through a tutorial that I found online and received the issue:

Implicit conversion loses integer precision: 'unsigned long' to 'int'

I have looked through some of the other post and haven't found one that helped me yet. I am new to programming and I would greatly appreciate any helpful advice!

This is the part where I am getting the issue:

- (void)handleTouchAtLocation:(CGPoint)touchLocation {
    if (!self.editable) return;

    int newRating = 0;
    for(int i = self.imageViews.count - 1; i >= 0; i--) {
        UIImageView *imageView = [self.imageViews objectAtIndex:i];        
        if (touchLocation.x > imageView.frame.origin.x) {
            newRating = i+1;
            break;
        }
    }

    self.rating = newRating;
}

This is the top part of my .h file:

#import "RWTRateView.h"

@implementation RWTRateView

@synthesize notSelectedImage = _notSelectedImage;
@synthesize halfSelectedImage = _halfSelectedImage;
@synthesize fullSelectedImage = _fullSelectedImage;
@synthesize rating = _rating;
@synthesize editable = _editable;
@synthesize imageViews = _imageViews;
@synthesize maxRating = _maxRating;
@synthesize midMargin = _midMargin;
@synthesize leftMargin = _leftMargin;
@synthesize minImageSize = _minImageSize;
@synthesize delegate = _delegate;

These are my property statements:

@property (strong, nonatomic) UIImage *notSelectedImage;
@property (strong, nonatomic) UIImage *halfSelectedImage;
@property (strong, nonatomic) UIImage *fullSelectedImage;
@property (assign, nonatomic) float rating;
@property (assign) BOOL editable;
@property (strong) NSMutableArray * imageViews;
@property (assign, nonatomic) int maxRating;
@property (assign) int midMargin;
@property (assign) int leftMargin;
@property (assign) CGSize minImageSize;
@property (assign) id <RWTRateViewDelegate> delegate;

Upvotes: 2

Views: 181

Answers (1)

matt
matt

Reputation: 535139

As you rightly say, this is the problem:

for (int i = self.imageViews.count - 1; i >= 0; i--) {

The problem is that self.imageViews.count is not an int. It is an NSUInteger, which is a very different animal. Simply rewrite:

for (NSUInteger i = self.imageViews.count - 1; i >= 0; i--) {

In particular, this conversion can cause issues across the bitness barrier. An NSUInteger changes its size depending whether we are on 32-bit or 64-bit. But int does not. The two are not compatible.

Upvotes: 1

Related Questions