简体   繁体   中英

compare two NSDate fails

I try to compare two NSDate objects. But it fails all the time and I can not see what is wrong.

  -(IBAction)nextAction
{
    NSDate *today = [NSDate date];
    if([appStateDate compare:today] == NSOrderedAscending) {
        dispatch_async(calcQueue, ^{ [self plusOneDate]; });
    }
}

Without the code it works fine.

it just crashes, and EXE_BAD_ACCESS on this line in the main method.

 int retVal = UIApplicationMain(argc, argv, nil, nil);

And prints

'+[ compare:]: unrecognized selector sent to class 0x634d7e0`'

Im not good at using the debugger, so if you know any good tutorials or guides i like to know them to ;) sorry for my english

Looks like appStateDate is not initialized, or contains something other than a NSDate. Where do you intitialize it?

to compares 2 NSDate dates:

NSDate *date1; NSDate *date2;
if ([date1 timeIntervalSinceDate:date2] > 0) 
    // date1 is newer.

From this topic, I would say like @Seva-Alekseyev, in -(IBAction)nextAction , appStateDate doesn't look like it's declared/initialized.

Maybe you should write what you already have in your -(void)plusOneDate method.

Just to check, you can also NSLog the type of variable and the value of appStateDate to see if it is what it's supposed to be.

I'm a beginner too, I'm not sure, but just trying to help :)

First of all, I strongly suggest you to look at the Memory Management Programming Guide to get a better knowledge of memory management.

It appears to me that appStateDate is not longer instance of NSDate class due to the way you are allocating it. When you use [NSDate date] you are actually saying [[[NSDate alloc]init]autorelease] so that object gets released before you can actually make use of it. Normally what you want to do with class instance objects is to alloc and init them, and then release them in the dealloc method.

I hope it helps you

It was actually the today that was the problem. The memory addr was in the console and i hovered over the objects to find the one matching. I just retained it, and released it in the end of the method. Thanks for all your answers ;)

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