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.
if you are trying to figure if elements from one array is present in another, you can try the following