Search code examples
iosobjective-cstringenumerationspritebuilder

Replacing Occurrences of Strings in NSMutableArray Only Working Once


I am confounded, and perhaps have missed something simple, but I can't find it.

I'll do this problem in theoretical, because I have done a test and still cannot get it to work with stripped down code. I am using SpriteBuilder, but that shouldn't be what is causing the issue - I can log the value I am getting in the text input, but simply cannot get that value into the array a second time - but enough ranting, time for some code.

Main.h

#import "Content.h"
#import "ReplaceMe.h"

@property Content *contentInstance;
@property ReplaceMe *replaceMeInstance; 

Main.m

   -(void)someFunction{
    _contentInstance = (Content*)[CCBReader load:@"ContentScene"];
  [_contentInstance.changeArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if ([_contentInstance.base[idx] containsString:@"one"]){
            NSLog(@"I contain one!");
            NSString *replace = [_content.testArray[idx] stringByReplacingOccurrencesOfString:@"one" withString:changeTheText.string];
            [_content.testArray replaceObjectAtIndex:idx withObject:replace];
            NSLog(@"%@",_content.testArray[idx]);
        }
    }];
[_contentInstance updateLabels];
    }

Content.h

@property NSArray *base;
@property NSArray *changeArray;

Content.m

-(void)someFunction{
    _base = @[@"This is one",@"This is two",@"This is two point one"];
    _changeArray = [base mutableCopy];
}
-(void)updateLabels{
    [_changeArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        _labeler = [CCLabelTTF labelWithString:[NSString stringWithFormat:@"%@",_changeArray[idx]] fontName:@"Helvetica" fontSize:12.0f];
        }
    }];
}

ReplaceMe.h

@property CCTextField *changeTheText;
-(void)_changeTheTextSelector;

ReplaceMe.m

-(void)_changeTheTextSelector{
self.visible=NO;
}

When I call MainScene's someFuction, this set up works just dandy the first time - and only the first time. I can't get changeArray to update after the first time I run the enumeration.

I know that changeTheText is changing, as it logs out, but when I log changeArray[idx], it is stuck at the first changeTheText.

Any ideas?


Solution

  • try this and compare with your code. it is working fine for me;

    NSArray* base = @[@"This is one",@"This is two",@"This is two point one"];
    NSMutableArray *changeArray = [base mutableCopy];
    
    [base enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if ([obj containsString:@"one"]) {
            NSLog(@"data : %@", changeArray[idx]);
            //--
            [changeArray replaceObjectAtIndex:idx withObject:[((NSString*) obj) stringByReplacingOccurrencesOfString:@"one" withString:@""]];
        }
    }];
    
    NSLog(@"changeArray %@", changeArray);