1

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!

4 Answers 4

2

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
}
Sign up to request clarification or add additional context in comments.

Comments

1

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:@","];

Comments

0

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

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

2 Comments

it's an example, suppose you have to do something more than removing a leading space.
Don't really understand what you are looking for. Are you asking for better ways to access the objects in the array?
0

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:@","];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.