2011-08-30 40 views
11

我想在的NSMutableArrayobjective-c:如何更新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; 
     } 
    } 

我想知道,如果有什么更好的办法做到这一点,以更新的对象?

回答

35

删除线

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

,这将是OK!

+0

是 - “但为什么”? – 2011-08-30 06:56:21

+4

因为[NSArray objectAtIndex:index]返回指向对象的指针。 – Nekto

+5

使用objectAtIndex检索值,修改它,然后使用replaceObjectAtIndex更好。 – afollestad

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

+3

+1命名约定 –

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

使用-insertObject:atIndex:replaceObjectAtIndex:withObject:

相关问题