如何在NSMutableArray中更新对象?

时间:2011-08-30 06:50:55

标签: ios objective-c nsmutablearray

我正在尝试更新 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;
    }
}

有没有更好的方法呢?

5 个答案:

答案 0 :(得分:36)

删除行:

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

那就没事了!

答案 1 :(得分:20)

要进行更新,请使用

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

但在这种情况下不需要它,因为你正在修改同一个对象。

答案 2 :(得分:10)

您可以先使用fast enumeration开始,这样更快更容易阅读。此外,您不需要删除和插入对象,您可以直接编辑它。像这样:

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

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

ProductList是一个对象吗?如果是,它应该以小写字母开头:productList。大写的名称用于类。此外,StatusQuantity是属性,也应该以小写字母开头。我强烈建议您遵循Cocoa naming conventions。)

答案 3 :(得分:6)

使用-insertObject:atIndex:replaceObjectAtIndex:withObject:

答案 4 :(得分:5)

有两种方法

  1. 创建一个新对象并用新对象替换旧对象
  2. 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;
           } 
    
         }
    

    更新现有对象:

    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;
            }
        }
    
相关问题