Wednesday, 3 June 2015

Difference between "==" and "isEqual:" in objective C

These two operators or function can be used to check equity of objects or operands. "==" is used to check if pointer values of objects are same. However "isEqual:" is used to test if both objects are having same values. So "==" works on reference and "isEqual" works on value. It can be easily understand by following example:
  1. NSMutableArray *array1 = [[NSMutableArray alloc]initWithObjects:@"A", @"B", nil];
  2. NSMutableArray *array2 = [[NSMutableArray alloc]initWithObjects:@"A", @"B", nil];
  3. if (array1 == array2) {
  4. NSLog(@"==");
  5. }
  6. if ([array1 isEqual:array2]) {
  7. NSLog(@"isequal");
  8. }
It will print "isEqual" because pointer values for both array1 and array2 are different
Second case:
  1. NSMutableArray *array1 = [[NSMutableArray alloc]initWithObjects:@"A", @"B", nil];
  2. NSMutableArray *array2 = [[NSMutableArray alloc]init];
  3. array2 = array1;
  4. if (array1 == array2) {
  5. NSLog(@"======");
  6. }
  7. if ([array1 isEqual:array2]) {
  8. NSLog(@"isequal");
  9. }
It will print "isEqual" and "==" because reference and value for both array1 and array2 are same
Third case:
  1. NSMutableArray *array1 = [[NSMutableArray alloc]initWithObjects:@"A", @"B", nil];
  2. NSMutableArray *array2 = [[NSMutableArray alloc]init];
  3. array2 = [array1 mutableCopy];
  4. [array1 addObject:@"C"];
  5. if (array1 == array2) {
  6. NSLog(@"======");
  7. }
  8. if ([array1 isEqual:array2]) {
  9. NSLog(@"isequal");
  10. }
It will print nothing because reference and value for both array1 and array2 are changed

For such more Blogs you can visit to http://findnerd.com/NerdDigest

No comments:

Post a Comment