Andreas Eriksson
Andreas Eriksson

Reputation: 9027

Objective-C += equivalent?

Sorry for the newbie question, but i cannot find an answer to it.

I have a simple operation. I declare a variable, and then i want to loop through an array of integers and add these to the variable. However, i can't seem to find how to get a += equivalent going in Objective C.

Any help would be awesome.

Code:

NSInteger * result;
for (NSInteger * hour in totalhours)
{
    result += hour; 
}

Upvotes: 0

Views: 164

Answers (6)

user756245
user756245

Reputation:

No problem using the '+=' operator, just be sure about the objects you are working with... Your code might be :

NSNumber *n; NSUInteger t = 0;
for(n in totalHours) {
    t += [n integerValue];
}
// you got your total in t...

Upvotes: 1

dreamlax
dreamlax

Reputation: 95315

The problem is that you are confusing NSInteger (a typedef for int or long) with a class instance such as NSNumber.

If your totalhours object is an array of NSNumber objects, you'll need to do:

NSInteger result;
for (NSNumber *hour in totalhours)
{
    result += [hour integerValue];
}

Upvotes: 1

Eiko
Eiko

Reputation: 25632

NSInteger is not a class, it's a typedef for int. You cannot put it into collections like NSArray directly.

You need to wrap your basic data types (int, char, BOOL, NSInteger (which expands to int)) into NSNumber objects to put them into collections.

NSInteger does work with +=, keep in mind that your code uses pointers to them, which is probably not what you want anyway here.

So

NSInteger a = 1, b = 2; 
a += b; 

would work.

If you put them with [NSNumber numberWitInt:a]; etc. into an NSArray, this is not that easy and you need to use -intValue methods to extract their values first.

Upvotes: 7

nall
nall

Reputation: 16129

If totalhours actually contains NSNumber objects you need the following:

NSInteger result = 0;
for(NSNumber* n in totalhours)
{
    result += [n integerValue];
}

Upvotes: 2

André Morujão
André Morujão

Reputation: 7133

Your problem is probably that you're using a pointer to an NSInteger instead of an actual NSInteger. You're also not initializing it. Try this:

NSInteger result = 0;
for (NSInteger * hour in totalhours)
{
    result += *hour; 
}

Upvotes: -2

ABeanSits
ABeanSits

Reputation: 1725

The += operation definitly works. All you need to do is initialize your result variable so it has a start value. E.g. NSInteger * result = 0;

Good luck!

Upvotes: -2

Related Questions