Matt
Matt

Reputation: 2843

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.

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'

Upvotes: 1

Views: 2040

Answers (2)

Jesse Naugher
Jesse Naugher

Reputation: 9820

Looks like one of your Objects doesn't have an name set correctly

Upvotes: 1

eliego
eliego

Reputation: 2289

One or more of the objects in objectList has it's name property set to nil. This leads to you trying to insert just nil into objectNames, which gives you the exception.

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:

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

Upvotes: 4

Related Questions