-3

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.

Muju
  • 884
  • 20
  • 54

5 Answers5

1

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"
    }
}
  • Not work it is'n cone in the block. – Muju Dec 19 '16 at 06:26
  • @Muju what ? , the code is working correctly, unless you have other datatypes inside the array (not NSStrings) , then it depends whether they are user defined classes or not , if they were user defined classes then you need to override the isEqual method inside your class , if not the code should work correctly – Abd Al-rhman Taher Badary Dec 19 '16 at 06:36
  • I have added something like this NSString * element = [NSString stringWithFormat:@"%@",[firstArray objectAtIndex:index]]; in your code and it work.But – Muju Dec 19 '16 at 06:44
  • But on the else part i need to insert value and it inset the value according to first array count.But I only want to insert one value and update only one element. – Muju Dec 19 '16 at 06:46
  • How to do the same thing without loop.Your answer is correct but.I want without for loop. – Muju Dec 19 '16 at 07:18
  • @Muju okay, when you reach that value you can call break; to stop the loop, and please if my answer helped you mark it as correct. – Abd Al-rhman Taher Badary Dec 19 '16 at 08:45
  • @ Abd Al-rhman Taher Badary But when I add break it only pic value at first index. If I pick other value then it crash, – Muju Dec 19 '16 at 09:24
  • You should break only when you find the needed value – Abd Al-rhman Taher Badary Dec 19 '16 at 09:30
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/130932/discussion-between-muju-and-abd-al-rhman-taher-badary). – Muju Dec 19 '16 at 10:19
1
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.

Er. Vihar
  • 1,495
  • 1
  • 15
  • 29
  • When I am using your code without for loop. its if block not execute. – Muju Dec 19 '16 at 08:42
  • After your reply I have tried my code without if condition. It's get execute. I have considered that You have only one object in your second, otherwise you must loop one of the array to get the accurate result. Hope you got the point and may solve the issue. – Er. Vihar Dec 19 '16 at 11:15
0

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.
   }
}
vaibhav
  • 4,038
  • 1
  • 21
  • 51
  • @vainhav I dont want to use loop. – Muju Dec 19 '16 at 09:54
  • y?. here seniors already put your ques on hold because of unforeseen situation, as i understand its a simple issue and you can do it by own. – vaibhav Dec 19 '16 at 09:58
  • @vainbhav because it insert data until loop runs. – Muju Dec 19 '16 at 10:00
  • @Muju there is no insertion in my ans as you questioned here, first decide your dependencies and clear you doubts. – vaibhav Dec 19 '16 at 10:11
  • Please see the full question. In if condition I am updating my code and in else condition in am inserting. – Muju Dec 19 '16 at 10:13
  • then where do you need to compare two arrays? and which one ? – vaibhav Dec 19 '16 at 10:19
  • I need to compare two array in didselectrowatindexpath method arr1 and arr2. – Muju Dec 19 '16 at 10:22
  • then you can put this code inside `didselectrowatindexpath` method at specific cells or common. – vaibhav Dec 19 '16 at 10:25
  • @vibhav Yes I am putting this code for a specific cell. But when I am using for loop it insert value so many times until loop runs.So, can I do this without using loop. – Muju Dec 19 '16 at 10:32
  • @vinhav Can you please answer my question http://stackoverflow.com/questions/43539307/how-to-post-string-with-special-character-and-thai-language-using-xml-parsing-in – Muju Apr 22 '17 at 06:41
0

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;
    }];
}
Chris.W
  • 15
  • 3
0

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

CRD
  • 52,522
  • 5
  • 70
  • 86