Reputation: 20670
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
Reputation: 17877
Remove lines:
[ProductList removeObjectAtIndex:i];
[ProductList insertObject:prod atIndex:i];
and that will be ok!
Upvotes: 39
Reputation: 10393
There are two approaches
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
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
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