Azhar
Azhar

Reputation: 20670

How do I update an object in NSMutableArray?

I am trying to update an object in NSMutableArray.

Product *message = (Product*)[notification object];
Product *prod = nil;

for(int i = 0; i < ProductList.count; i++)
{
    prod = [ProductList objectAtIndex:i];
    if([message.ProductNumber isEqualToString:prod.ProductNumber])
    {
        prod.Status = @"NotAvaiable";
        prod.Quantity = 0;
        [ProductList removeObjectAtIndex:i];
        [ProductList insertObject:prod atIndex:i];
        break;
    }
}

Is there any better way to do this?

Upvotes: 13

Views: 25830

Answers (5)

Nekto
Nekto

Reputation: 17877

Remove lines:

[ProductList removeObjectAtIndex:i];
[ProductList insertObject:prod atIndex:i];

and that will be ok!

Upvotes: 39

Zverusha
Zverusha

Reputation: 317

Use -insertObject:atIndex: or replaceObjectAtIndex:withObject:.

Upvotes: 6

Praveen S
Praveen S

Reputation: 10393

There are two approaches

  1. Create a new object and replace the old object with the new object
for(int i = 0; i < ProductList.count; i++)         
   {
      prod = [ProductList objectAtIndex:i];
      if([message.ProductNumber isEqualToString:prod.ProductNumber])
       {
           newObj = [[Product alloc] autorelease];
           newObj.Status = @"NotAvaiable";
           newObj.Quantity = 0;
           [ProductList replaceObjectAtIndex:i withObject:newObj];
           break;
       } 

     }

Update the existing object:

for(int i = 0; i < ProductList.count; i++)
    {
        prod = [ProductList objectAtIndex:i];
        if([message.ProductNumber isEqualToString:prod.ProductNumber])
        {
            prod.Status = @"NotAvaiable";
            prod.Quantity = 0;
            break;
        }
    }

Upvotes: 5

Pontus Granstr&#246;m
Pontus Granstr&#246;m

Reputation: 1089

You could start by using fast enumeration, which is faster and easier to read. Also, you don't need to remove and insert the object, you can just edit it in line. Like this:

Product *message = (Product*)[notification object];

for(Product *prod in ProductList)
{
    if([message.ProductNumber isEqualToString:prod.ProductNumber])
    {
        prod.Status = @"NotAvailable";
        prod.Quantity = 0;
        break;
    }
}   

(Is ProductList an object? If it is, it should start with a lowercase letter: productList. Capitalized names are for classes. Also, Status and Quantity are properties and should too start with a lowercase letter. I highly suggest you follow the Cocoa naming conventions.)

Upvotes: 11

KingofBliss
KingofBliss

Reputation: 15115

For updating, use

- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject

But it is not needed in this case, since you are modifying the same object.

Upvotes: 21

Related Questions