简体   繁体   English

使用ForEach循环添加对象NSMutableArray

[英]Adding Object NSMutableArray with ForEach Loop

here is what i am trying to do: 这是我想做的事情:

NSMutableArray *objectNames = [[NSMutableArray alloc] init];
for (Object *o in objectList){
    if (![objectNames containsObject:o.name]) {
        [objectNames addObject:o.name];
    }
}

I am trying to go through an array of objects, then take the objects name (a string) and add it to a string array of objectNames. 我正在尝试遍历对象数组,然后获取对象名称(字符串)并将其添加到objectNames的字符串数组中。

This code works in the simulator just fine. 这段代码可以在模拟器中正常工作。 but when i run it on the device i get this error. 但是当我在设备上运行它时,出现此错误。

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSCFArray insertObject:atIndex:]: attempt to insert nil'

One or more of the objects in objectList has it's name property set to nil. objectList中的一个或多个对象的name属性设置为nil。 This leads to you trying to insert just nil into objectNames, which gives you the exception. 这导致您尝试仅将nil插入objectNames中,这给您带来了异常。

If it's OK for an object to have a name of nil, what you need to do is to check for this before you insert into objectNames: 如果一个对象的名称为nil可以,那么您需要做的是在插入objectNames之前进行检查:

NSMutableArray *objectNames = [[NSMutableArray alloc] init];
for (Object *o in objectList){
   if (name && ![objectNames containsObject:o.name]) {
      [objectNames addObject:o.name];
   }
 }

似乎您的一个对象的name设置不正确

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM