Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Difference between "==" and "isEqual:" in objective c

    • 0
    • 1
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.82k
    Comment on it

    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:

    NSMutableArray *array1 = [[NSMutableArray alloc]initWithObjects:@"A", @"B", nil];
    NSMutableArray *array2 = [[NSMutableArray alloc]initWithObjects:@"A", @"B", nil];
    if (array1 == array2) {
            NSLog(@"==");
        }
    if ([array1 isEqual:array2]) {
            NSLog(@"isequal");
        }

    It will print "isEqual" because pointer values for both array1 and array2 are different

    Second case:

    NSMutableArray *array1 = [[NSMutableArray alloc]initWithObjects:@"A", @"B", nil];
    NSMutableArray *array2 = [[NSMutableArray alloc]init];
    array2 = array1;
    if (array1 == array2) {
            NSLog(@"======");
        }
    if ([array1 isEqual:array2]) {
            NSLog(@"isequal");
        }

    It will print "isEqual" and "==" because reference and value for both array1 and array2 are same

    Third case:

    NSMutableArray *array1 = [[NSMutableArray alloc]initWithObjects:@"A", @"B", nil];
    NSMutableArray *array2 = [[NSMutableArray alloc]init];
    array2 = [array1 mutableCopy];
        [array1 addObject:@"C"];
        if (array1 == array2) {
            NSLog(@"======");
        }
        if ([array1 isEqual:array2]) {
            NSLog(@"isequal");
        }

    It will print nothing because reference and value for both array1 and array2 are changed

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: