How to compare two dynamic array in without using loop objective c

921 views Asked by At

I am new in iOS and I am facing a problem regarding to compare two array. I tried this code

 if ([arr1 isEqualToArray:arr2])
 {
      NSLog(@"Print the output to update...");
 }

But this not work for me.Because my array is like this

arr1=[@"1",@"2",@"3",@"4",@"5",@"6"];
arr2=[@"2"];

So, I tried a code like this

NSSet *set1 = [NSSet setWithArray:arr1];
NSSet *set2 = [NSSet setWithArray:arr2];

if ([set1 isEqualToSet:set2]) {
    // equal
}

But, this not work for me.In my case arr1 is from web service and arr2 is from core data.can you suggest any other suggestion to compare this two array.

In if condition I am updating my code and in else condition in am inserting

if([arr1 isEqualToArray:arr2])
{
   NSManagedObjectContext *context = [self managedObjectContext];

   NSFetchRequest *request = [[NSFetchRequest alloc] init];
   [request setEntity:[NSEntityDescription entityForName:@"EntityName"  inManagedObjectContext:context]];

   NSError *error = nil;
   NSArray *results = [context executeFetchRequest:request error:&error];
   NSManagedObject* favoritsGrabbed = [results objectAtIndex:0];
   [favoritsGrabbed setValue:@"1" forKey:@"Key"];
   // Save the object to persistent store
   if (![context save:&error]) {
      NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
   }
}
else
{
  if (self.device) {
                        // Update existing device
                        [device setValue:Audit forKey:@"key1"];
                        [device setValue:MethodID forKey:@"key2"];
                        [device setValue:CheckPointID forKey:@"key3"];
                        [device setValue:GlobalStringChk forKey:@"key4"];
                        [device setValue:RegionID forKey:@"key5"];
                        [device setValue:BranchID forKey:@"key6"];
                        [device setValue:SiteID forKey:@"key7"];
                        [device setValue:AuID forKey:@"key8"];
                        [device setValue:userid forKey:@"key9"];
                        [device setValue:StringIndex forKey:@"key10"];

                    } else {
                        // Create a new device
                        NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:@"EntityName" inManagedObjectContext:context];
                        [newDevice setValue:Audit forKey:@"key1"];
                        [newDevice setValue:MethodID forKey:@"key2"];
                        [newDevice setValue:CheckPointID forKey:@"key3"];
                        [newDevice setValue:GlobalStringChk forKey:@"key4"];
                        [newDevice setValue:RegionID forKey:@"key5"];
                        [newDevice setValue:BranchID forKey:@"key6"];
                        [newDevice setValue:SiteID forKey:@"key7"];
                        [newDevice setValue:AuID forKey:@"key8"];
                        [newDevice setValue:userid forKey:@"key9"];
                        [newDevice setValue:StringIndex forKey:@"key10"];
                    }
}

Hear,I need to compare array so that I can update the value in core data and if array are not equal then I need to insert them.So, I can not use loop.Please see its else condition if I used loop it insert data until loop runs and I want to insert one value at click.So, I can not use loop.

5

There are 5 answers

9
Abd Al-rhman Taher Badary On BEST ANSWER

if you are trying to figure if elements from one array is present in another, you can try the following

NSArray * firstArray = @[@"1",@"2",@"3",@"4"];
NSArray * secondArray = @[@"2",@"10",@"20"];

for(int index = 0 ; index < [firstArray count] ; index++)
{
    NSString * element = [firstArray objectAtIndex:index];
    if([secondArray containsObject:element])
    {
       //do stuff
       //This block will execute only when element == @"2"
    }
}
10
vaibhav On

Here are many ways.

Use nested loops to know the exact position of equal elements:

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

    for(int j= 0; j<arr1.count; j++){
        if(arr1[j] == arr2[i])
            NSLog(@"index position: %d element %@:", j, array1[j]);
    }

}

Or you can use containsObject: methods:

containsObject: Returns a Boolean value that indicates whether a given object is present in the array.

for(int i= 0; i<arr2.count; i++){
   if ([arr1 containsObject:[arr2 objectAtIndex:i]]) {
       // indicates whether a given object is present in the array.
   }
}
2
Er. Vihar On
for (int i = 0; i < array2.count; i++)
    {
        if ([array1 containsObject:[array2 objectAtIndex:i]])
        {
            NSLog(@"Array1 contains array2 object");
        }
        else
        {
            NSLog(@"Array1 do not contains array2 object");
        }
    }

You can try this. This is working for me with your above provided data.

1
Chris.W On

Try this

arr1=[@"1",@"2",@"3",@"4",@"5",@"6"];
arr2=[@"2"];

//compare result
BOOL bol = (arr1.count == arr2.count);

// if count equal
if (bol) {  

   for (NSInteger i = 0; i < arr1.count; i++) {  

       NSString *str1 = [arr1 objectAtIndex:i];  
       NSString *str2 = [arr2 objectAtIndex:i];  

       if (![str1 isEqualToString:str2]) {  
          bol = NO;  
          break;  
        }  
    }  
} 

or use block

NSArray *arr1=@[@"1",@"2",@"3",@"4",@"5",@"6"];
NSArray *arr2=@[@"2"];

//compare result
__block BOOL bol = (arr1.count == arr2.count);

// if count equal
if (bol) {

    [arr1 sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2) {
        if (![obj1 isEqualToString:obj2]) {
            bol = NO;
        }
        return NSOrderedAscending;
    }];
}
3
CRD On

From your comments and title I guess:

  1. By "compare" and "is equal" you are meaning to test membership; and
  2. Your second array only contains one item (so there is no need to loop)

If this is correct then change your line:

if([arr1 isEqualToArray:arr2])

to

if([arr1 containsObject:arr2[0]])

which checks whether arr1 contains the first element of arr2 (i.e. arr2[0]).

HTH