迭代 NSMutableArray 时修改对象

问题描述 投票:0回答:4

我试图在迭代数组时修改数组中的对象,但找不到一个好的方法......这就是我所做的,有没有更简单的方法来做到这一点?我已经用谷歌搜索了一段时间,但我找不到任何东西......

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];

谢谢!

ios objective-c
4个回答
2
投票

正如其他人所建议的,可能有更好的方法来完成问题中的确切任务,但作为一般模式,您的方法没有任何问题 - 构建一个新数组。

但是,如果您需要修改可变数组,比如说因为多个对象引用它,那也没有什么问题 - 这就是为什么它毕竟是可变的!您只需要使用标准迭代而不是枚举 - 后者只是不适合这项工作的工具。例如:

NSMutableArray *anArray = ...

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

1
投票

您这样做的方式是可以的,因为您没有修改正在循环的数组。

这是另一种方法,有点不太直观,而且可能不会更快:

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

0
投票

考虑到您的小时字符串类似于:2、5、6、7 等,您可以直接使用该字符串作为

@", "

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

0
投票

也许在分离之前消除所有空白会更好。

NSString *daysWithOutSpaces = [restaurant.hours stringByReplacingOccurrencesOfString:@"[\\s\\n]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, restaurant.hours.length)];
NSArray *days = [daysWithOutSpaces componentsSeparatedByString:@","];
© www.soinside.com 2019 - 2024. All rights reserved.