-2

How I can replace elements? I try like this, but it does not work

    NSMutableArray* marray = [[NSMutableArray alloc] initWithObjects:@"1", @"2", @"3", nil];

for (int i = 0; [marray count]; i++) {        
    NSInteger curentVal = [[marray objectAtIndex:i] intValue];
    curentVal += 5;
    [marray replaceObjectAtIndex:i withObject:curentVal];
}
3
  • 1
    not related but don't you need i < [marray count]; in your for loop? Commented Jan 22, 2015 at 0:27
  • 1
    There were no error messages when you tried to compile the above?? Commented Jan 22, 2015 at 0:46
  • Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Commented Jan 22, 2015 at 0:47

2 Answers 2

2

You need to convert curentVal back to an object, in this case a NSString.

There is also a typeo in the for statement.

NSMutableArray* marray = [[NSMutableArray alloc] initWithObjects:@"1", @"2", @"3", nil];
NSLog(@"marray: %@", marray);

for (NSInteger i = 0; i<[marray count]; i++) {
    NSInteger curentVal = [[marray objectAtIndex:i] intValue];
    curentVal += 5;
    NSString *curentValString = [NSString stringWithFormat:@"%ld", (long)curentVal];
    [marray replaceObjectAtIndex:i withObject: curentValString];
}
NSLog(@"marray: %@", marray);

Output:

marray: (
    1,
    2,
    3
)
marray: (
    6,
    7,
    8
)

Here is the same approach with NSNumbers:

NSMutableArray* marray = [[NSMutableArray alloc] initWithObjects:@1, @2, @3, nil];
for (NSInteger i = 0; i<[marray count]; i++) {
    NSInteger curentVal = [[marray objectAtIndex:i] intValue];
    curentVal += 5;
    [marray replaceObjectAtIndex:i withObject:@(curentVal)];
}
Sign up to request clarification or add additional context in comments.

2 Comments

But they are starting with strings, not numbers.
One more suggestion - change i to NSInteger instead of int.
1

curentVal is not an object. You should put:

 [marray replaceObjectAtIndex:i withObject:@(curentVal)];

so curentVal is converted to an NSNumber

Also you probably want to deal with numbers, so put:

NSMutableArray* marray = [[NSMutableArray alloc] initWithObjects:@1, @2, @3, nil];

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.