Andres
Andres

Reputation: 11747

Modify Object while Iterating over a NSMutableArray

I was trying to modify an object from an array while iterating over it and couldn't find a nice way of doing it... This is what I've done, is there a simpler way of doing this? I've been googling for while but I couldn't find anything...

NSMutableArray *tempArray = [[NSMutableArray alloc]init];
NSArray *days = [restaurant.hours componentsSeparatedByString:@","];
for (NSString *day in days) {
      NSString *dayWithOutSpace = [day stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
      [tempArray addObject:dayWithOutSpace];
}
days = [NSArray arrayWithArray:tempArray];

Thanks!

Upvotes: 1

Views: 1165

Answers (4)

CRD
CRD

Reputation: 53000

As suggested by others there might be better ways to accomplish the exact task in the question, but as a general pattern there is nothing wrong with your approach - build a new array.

However if you need to modify a mutable array, say because multiple objects reference it, there is nothing wrong with that either - that is why it is mutable after all! You just need to use standard iteration rather than enumeration - the latter is just the wrong tool for the job. E.g.:

NSMutableArray *anArray = ...

NSUInteger itemCount = [anArray count];
for(NSUInteger ix = 0; ix < itemCount; ix++)
{
   // read from anArray[ix] and store into anArray[ix] as required
}

Upvotes: 2

malex
malex

Reputation: 10096

Maybe it is better to eliminate all white spaces before separation.

NSString *daysWithOutSpaces = [restaurant.hours stringByReplacingOccurrencesOfString:@"[\\s\\n]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, restaurant.hours.length)];
NSArray *days = [daysWithOutSpaces componentsSeparatedByString:@","];

Upvotes: 0

Odrakir
Odrakir

Reputation: 4254

The way you do it is OK, since you are not modifying the array you are looping through.

Here is another way, a little less intuitive and probably not faster:

NSArray* days = [[[restaurant.hours componentsSeparatedByString:@" "] componentsJoinedByString:@""] componentsSeparatedByString:@","];

Upvotes: 1

Anindya Sengupta
Anindya Sengupta

Reputation: 2579

Considering your hours string is like: 2, 5, 6, 7 etc. you can use the string as @", " directly.

NSArray *days = [restaurant.hours componentsSeparatedByString:@", "];

Upvotes: 0

Related Questions