如何在NSMutableArray中更新对象?

问题描述 投票:11回答:5

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

有没有更好的方法来做到这一点?

ios objective-c nsmutablearray
5个回答
36
投票

删除行:

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

那没关系!


20
投票

要更新,请使用

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

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


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


6
投票

使用-insertObject:atIndex:replaceObjectAtIndex:withObject:


5
投票

有两种方法

  1. 创建一个新对象并用新对象替换旧对象
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;
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.