简体   繁体   中英

Compare two NSMutableArray indices in iPhone

I am new to iPhone develepment,

I want to compare two array indices,

for (int i=0; i<[CustomeDateArray count]; i++)
  {
      if (([CustomeDateArray objectAtIndex:1] == [newDateArray objectAtIndex:1]) && ([CustomeDateArray objectAtIndex:2] == [newDateArray objectAtIndex:2]))          
                {
                    exists=TRUE;
                    NSLog(@"exists=TRUE");
                }
  }

My Log shows this Results:

 CustomeDateArray at Index1=06
 CustomeDateArray at Index2=2012

 newDateArray at Index1=06
 newDateArray at Index2=2012

If my if condition is true then control should go inside and it should print exists=TRUE but i am unable to see exists=TRUE control is not going inside.

What's the problem ?

Any help will be appreciated.

for (int i=0; i<[CustomeDateArray count]; i++)
  {
          if (([[CustomeDateArray objectAtIndex:1] isEqual:[newDateArray objectAtIndex:1]]) && ([[CustomeDateArray objectAtIndex:2] isEqual:[newDateArray objectAtIndex:2]]))        
                {
                    exists=TRUE;
                    NSLog(@"exists=TRUE");
                }
  }

This May Helping to you Happy Coding:-)

Well, I see to kind of problems in your code:

  1. why you are looping inside CustomDateArray (for loop) and you are not using the index "i"? (this is not relevant to the specific question, but just check your code for typos!)

  2. more specific to your question: NSArray contains objects and objects in Obj-C are pointers, so your "==" just compares pointers. This means that:

if([CustomDateArray objectAtIndex:1]==[CustomDateArray objectAtIndex:2]) ...

corresponds to:

id obj1 = [CustomDateArray objectAtIndex:1];
id obj2 = [CustomDateArray objectAtIndex:2];
if(obj1==obj2) ...

The "if" will return true only if obj1 and obj2 point to the same address, so they are exactly the same object. But if the purpose of your check is to know if the two dates are the same date, then you should use the NSDate specific comparison methods:


NSDate *d1 = [CustomDateArray objectAtIndex:1];
NSDate *d2 = [CustomDateArray objectAtIndex:2];
if([d1 isEqualToDate:d2]) ...

Instead, if the objects are string, you should use the "isEqualToString:" method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM