snapfish
snapfish

Reputation: 175

int or NSInteger to NSUInteger for index

I'm trying to (in Xcode5) use the 'removeObjectAtIndex' for an 'MutableArray' which takes an NSUInteger but the variable I'm using is an integer so I casted with (NSUInteger *) but I get a warning that says cast to 'NSUInteger *' (aka unsigned long *) from smaller integer type. I have not casted the variable 'second' in the code to keep the warning there but it is also an integer

-(void) moveObjectAtIndex:(NSUInteger *)oldIndex toNewIndex:(NSUInteger *)newIndex{
    id *member = [self.array objectAtIndex:*oldIndex];
    [self.array removeObjectAtIndex:*oldIndex];
    if ((NSInteger)newIndex >=(self.array.count)) {
        newIndex--; //i casted newIndex because I got a warning about ordered comparison of NSUInteger with NSInteger (I'm not sure if this is best solution)
    }
    [self.array insertObject:member atIndex: *newIndex];
}

-(void)moveObjectInArray:(NSMutableArray *)array{
    [array moveObjectAtIndex:(NSUInteger *) first toNewIndex:second];
}

Upvotes: 0

Views: 1201

Answers (3)

simalone
simalone

Reputation: 2768

What's problem for you of using just NSUInteger rather than NSUInteger* ?

-(void) moveObjectAtIndex:(NSUInteger)oldIndex toNewIndex:(NSUInteger)newIndex{
    id member = [self.array objectAtIndex:oldIndex]; //Here is id, id* is wrong
    [self.array removeObjectAtIndex:oldIndex];
    newIndex = newIndex >= self.array.count ? : self.array.count - 1; // Here should be self.array.count - 1, not newIndex-1
    newIndex = MIN(_cloudListArray.count, newIndex);
    [self.array insertObject:member atIndex:newIndex];
}

Upvotes: 2

Chuck
Chuck

Reputation: 237060

Your use of pointers is all wonky. id* should just be id and NSUInteger* should just be NSUInteger — you don't want a pointer to a pointer to an object or a pointer to an integer here.

Upvotes: 3

doptimusprime
doptimusprime

Reputation: 9395

In the following statement

if ((NSInteger)newIndex >=(self.array.count))

you are typecasting pointer to NSInteger. It should be

if ((NSInteger)*newIndex >=(self.array.count))

Still, you should be careful with typecasting and be wary of their consequences due to any signed/unsigned conversion or data loss.

Also, in this line

[array moveObjectAtIndex:(NSUInteger *) first toNewIndex:second];

type of first should be NSUInteger * or of same size. Please note that long is 64-bit in 64-bit environment and typecasting as smaller pointer type to larger pointer type will yield undefined behaviour. Same applies to second. One solution is that use temporary variable and then copy back the result.

Upvotes: -1

Related Questions