How to send values to Ivar in method

88 Views Asked by At

new to Objective-C and keeping it very very simple I'm looking to understand one thing at a time... I set up a very simple class called student all it does is add two numbers trying to see how things pass into and back from methods) **I rewrote the code ==>> look at end to see the version that works **

If I have a method that has

@property (nonatomic) int firstNum; 
@property (nonatomic) int secondNum;

and I have an instance of my class called student I assign a value to firstNum like student.firstNum = 100; student.secondNum = 77; that is easy and the method adds them and sends the sum in a return

But in main I tried assigning it from an array and it did not work I tried

student.firstNum = [myIntegers objectAtIndex:0];

and

student.firstNum = [myIntegers objectAtIndex:i]; //using a for loop with i index 

it says incompatible pointer to integer conversion

Here is the snippet from main I tried it's not complete it just is trying to set firstNum eventually I will also set up secondNum and send each pair to the method to get added together but for now I am stuck trying to get the firstNum assigned the value in myIntegers[i] to start

NSMutableArray *myIntegers = [NSMutableArray array];

for (NSInteger i= 0; i <= 10; i++) {

    [myIntegers addObject:[NSNumber numberWithInteger:i]]; // this works up to here 

    student.firstNum = [myIntegers objectAtIndex:i]; // this does not work

} 

I also tried [i].

Here is my method:

- (int)addNumbers {

    int sum = self.firstNum + self.secondNum;
    return sum;
}

HERE IS WHAT WORKS : assuming I have a student object

.m

  • (long)addNumbers:(NSNumber *)x :(NSNumber *)y {

    long sum;

    sum = [x integerValue] + [y integerValue]; return sum; }

main

NSMutableArray *myIntegers1 = [NSMutableArray array]; NSMutableArray *myIntegers2 = [NSMutableArray array];

    for (NSInteger  i= 0; i <40; i++) {

        [myIntegers1 addObject:[NSNumber numberWithInteger:i]];
        [myIntegers2 addObject:[NSNumber numberWithInteger:i]];

long sum = [student addNumbers:[myIntegers1 objectAtIndex:i] :[myIntegers2 objectAtIndex:i]];

        NSLog(@" The sum is %ld", sum);
}
1

There are 1 best solutions below

2
AMI289 On

You are creating a properties of type int, but in your for loop, you are trying to assign them an NSNumber.

NSNumber is a simple container for a c data item and can hold int, float, char, bool, etc.

Change your loop to be like that:

for (NSInteger  i= 0; i <= 10; i++) {

    [myIntegers addObject:[NSNumber numberWithInteger:i]];

    student.firstNum = [[myIntegers objectAtIndex:i] intValue]; // this 'extracts' the int value from the NSNumber

}