Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Hi I'm building an iPhone app which loads a html string from a local file and edits it. This htm file contains a table that contains multiple cells. The contents of each cell is cell0, cell1, cell2, cell3, etc...

What I'm doing is replacing the contents of those cells with data from the array. I first search for the string in the htm file and replace it with a string from the array as such:

[modifiedHtm replaceOccurrencesOfString:@"cell0" withString:[array objectAtIndex:0] options:0 range:NSMakeRange(0, modifiedHtm.length)];
[modifiedHtm replaceOccurrencesOfString:@"cell1" withString:[array objectAtIndex:1] options:0 range:NSMakeRange(0, modifiedHtm.length)];
[modifiedHtm replaceOccurrencesOfString:@"cell2" withString:[array objectAtIndex:2] options:0 range:NSMakeRange(0, modifiedHtm.length)];
[modifiedHtm replaceOccurrencesOfString:@"cell3" withString:[array objectAtIndex:3] options:0 range:NSMakeRange(0, modifiedHtm.length)];

Each cell is replaced by the corresponding object from the array, i.e. cell2 is replaced by object 2 of the array.

This array is quite long and I have several of them, each with varying amounts of objects.

Is there a way to tell it to replace occurrence of string "cell(n)" with String [array objectAtIndex:(n)] where n is an integer between 0 and say 75?

share|improve this question
    
Well, the ofString value can be a variable which you calculate with a stringWithFormat statement. –  Hot Licks yesterday

1 Answer 1

up vote 1 down vote accepted

There is no such a method, but you can easily do it manually by putting it into the loop, like this:

for (int i = 0; i < array.count; i++) {
    NSString *cellString = [NSString stringWithFormat:@"cell%d", i];
    [modifiedHtm replaceOccurrencesOfString:cellString withString:[array objectAtIndex:i] options:0 range:NSMakeRange(0, modifiedHtm.length)];
}

If you do it for every cell, just to display it in cell, the best solution is to put it in cellForRowAtIndexPath: method:

NSString *cellString = [NSString stringWithFormat:@"cell%d", indexPath.row];
        [modifiedHtm replaceOccurrencesOfString:cellString withString:[array objectAtIndex:indexPath.row] options:0 range:NSMakeRange(0, modifiedHtm.length)];

Hope this help.

share|improve this answer
    
Brilliant! That worked, Thank you very much!! –  jcooper_82 yesterday

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.