-1

I have an NSMutableArray of objects which are of AdDetail class that hold a few properties (for eg. adId, adTitle, adPrice... etc). I want to remove only those objects which have adID = 0. How can I do that ?

Ankur Arya
  • 4,693
  • 5
  • 29
  • 50
  • 2
    use predicate to filter the list/array.. – vishy Apr 03 '13 at 09:37
  • why is everybody down-voting this question? – Ankur Arya Apr 03 '13 at 11:57
  • There are many posts and samples to work out filtering array using NSPredicate.. some of below posts will help u.. http://stackoverflow.com/questions/7207050/searching-filtering-a-custom-class-array-with-a-nspredicate http://stackoverflow.com/questions/3386079/use-nspredicate-to-filter-by-object-attribute – vishy Apr 03 '13 at 09:39

6 Answers6

12

Perhaps something more elegant would suffice?

[array removeObjectsInArray:[array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"adID == 0"]]];
Zack Brown
  • 5,990
  • 2
  • 41
  • 54
2

Using predicate

NSArray *filtered=[array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(adId == 0)"]];

Using fastEnumeration:

NSMutableArray *newArray=[NSMutableArray new];
for(AdDetail adDetailObj in array){
    if(![[adDetailObj adId] isEqualToString:@"0"]){ //if these are strings, if NSInteger then directly compare using ==
       newArray[newArray.count]=adDetailObj;
   }
}

Now newArray contains all objects other than id=0

Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140
1
NSMutableArray *newArray = [NSMutableArray arrayWithArray:yourArray];

for (int i = 0; i < yourArray.count; i++)
{
     AdDetail *obj = (AdDetail *)[yourArray objectAtIndex:i];
     if (obj.adID == 0)
         [newArray removeObjectAtIndex:i];
}
yourArray = [newArray mutableCopy];
Rushi
  • 4,553
  • 4
  • 33
  • 46
1
for(i=0; i < myArray.count; i++)
{
  myClass = [myArray objectAtIndex:i];
  if([myClass.adID isEqualtoString:"0"])// if it it int/NSInteger the write myClass.adID==0
  {
            [myArray removeObjectAtIndex:i];
      i--;
  }
}
iPatel
  • 46,010
  • 16
  • 115
  • 137
1

Use following code :

int count = array.count;
for(i=0;i<count;i++){

     ADetail *adetail = [array objectAtIndex:i];
     if(adetail.adID = 0){

         [array removeObjectAtIndex:i];
          i--;

     }
     count = array.count;
}
Payal
  • 116
  • 3
0
predicate = @"adID == 0";
newArray = [theArray filterUsingPredicate:aPredicate]
msk
  • 8,885
  • 6
  • 41
  • 72