开发者

How do I update an object in NSMutableArray?

开发者 https://www.devze.com 2023-03-31 11:05 出处:网络
I am trying to update an object in NSMutableArray. Product *message = (Product*)[notification object];

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?


Remove lines:

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

and that will be ok!


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.


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.)


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


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;
        }
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消