Compare two NSDates for same date/time [duplicate]

别等时光非礼了梦想. 提交于 2019-11-28 08:25:29

You're comparing two pointer values. You need to use the NSDate comparison method like:

return ([date1 compare:date2] == NSOrderedSame);

As in the C language (of which Objective-C is a superset), the == (equality) operator compares two pointer values to see if they are equivalent (i.e. if two variables hold the same object). While this works in comparing primitive values (ints, chars, bools), it does not work on Objective-C objects, which might be equal in content, but differ in memory location (which is what the equality operator compares).

To check if two objects are equal, NSObject offers an -isEqual: method which you can use as a general statement (e.g. [date1 isEqual:date2]), and some classes choose to offer a more specific comparison method, such as -isEqualToDate: used to compare NSDates, or -isEqualToString: used to compare NSStrings. These methods cannot be used to compare primitive types (ints, for instance) because those are not objects, but will work on almost all objects.

You can't use == in Objective-C to compare object equality (it will take the C meaning, comparing pointers). Like other languages, you are simply comparing the object pointers.

The message you want is isEqualToDate:, aka [date1 isEqualToDate:date2]

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!