0

I am running this for loop which deletes an indexValue if a condition is met. I am comparing two NSDate objects and for some reason it is not working. According to the log the NSDate objects match exactly.

Please guide me here.

Code

for (int u=0 ; u<arraywithDateAddedKeyss.count ; u++)
        {
            NSLog(@"arraywithDateAddedKeyss: %@ == Array 5: %@",arraywithDateAddedKeyss[u],oldArray[5]);

            if (arraywithDateAddedKeyss[u] == oldArray[5])
            {
                [arraywithDateAddedKeyss removeObjectAtIndex:u];

                [userDefaults setObject:arraywithDateAddedKeyss forKey:@"arraywithReminderDateKeys"];

                [userDefaults synchronize];


                NSLog(@"Object Removed from array1");


            }
        }

NSLog data

arraywithDateAddedKeyss: 2014-02-01 09:01:20 +0000 == Array 5: 2014-02-01 09:01:20 +0000
Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235
Alik Rokar
  • 1,135
  • 1
  • 10
  • 16

4 Answers4

5

You cannot compare two dates using ==.

== compares pointer equality, meaning that you are checking for object identity rather than equality. (Worth reading on the subject: http://nshipster.com/equality/)

Use the isEqualToDate: method of NSDate for such purpose

NSDate *date1 = arraywithDateAddedKeyss[u];
NSDate *date2 = oldArray[5];

if ([date1 isEqualToDate:date2]) {
   ...
}

For other ways of comparing NSDate objects, you can refer to: How to compare two dates in Objective-C

Community
  • 1
  • 1
Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235
0

Change your if to isEqual, you should use it insteat of ==:

if ([arraywithDateAddedKeyss[u] isEqual:oldArray[5]])
{
    //Add this log for debuting
    NSLog(@"Dates are equal");
    //.. your code here
}

Hope this help.

Greg
  • 25,317
  • 6
  • 53
  • 62
0

You can't compare two pointer using == operator. Better use below code .. See apple's doc

NSDate *date = oldArray[5];
for(NSDate *dateToBeCompare in arraywithDateAddedKeyss)
{
    if ([date compare:dateToBeCompare] == NSOrderedSame)
    {
           //Your code here...
    }
}
Mani
  • 17,549
  • 13
  • 79
  • 100
0

Change your code to this:

 for (int u=arraywithDateAddedKeyss.count-1; u>=0 ; u--)
    {
        if ([arraywithDateAddedKeyss[u] compare:oldArray[5]] == NSOrderedSame)
        {
            [arraywithDateAddedKeyss removeObjectAtIndex:u];
            [userDefaults setObject:arraywithDateAddedKeyss forKey:@"arraywithReminderDateKeys"];
            [userDefaults synchronize];
        }
    }

NOTE: You must loop your array from the end to the beginning if you want to remove an object at some index

iOS Dev
  • 4,143
  • 5
  • 30
  • 58