У меня есть следующий объект:
#import <Foundation/Foundation.h>
typedef NS_ENUM(NSUInteger, SeasonType) {
kWinter,
kSpring,
kSummer,
kFall
};
@interface Season : NSObject
@property (nonatomic) SeasonType season;
@property (nonatomic) NSUInteger year;
+(id) seasonWithYear:(NSInteger)year season:(SeasonType)season;
-(id) initWithYear:(NSInteger)year season:(SeasonType)season;
@end
Что я делаю, так это перезаписываю базовые методы сравнения NSObject, нет необходимости заново изобретать колесо, а код также сохраняет чистоту:
#import "Season.h"
@interface Season()
@end
@implementation Season
+(id) seasonWithYear:(NSInteger)year season:(SeasonType)season{
return [[self alloc] initWithYear:year season:season];
}
-(id) initWithYear:(NSInteger)year season:(SeasonType)season{
self = [super init];
if (self)
{
_year = year;
_season=season;
_baseDate=nil;
}
return self;
}
#pragma mark - NSObject
- (BOOL)isEqual:(id)object {
if (self == object) {
return YES;
}
if (![object isKindOfClass:[Season class]]) {
return NO;
}
return [self _isEqualToSeason:(Season *)object];
}
- (NSUInteger)hash {
return self.season ^ self.year;
}
#pragma mark - Private/Internal
- (BOOL)_isEqualToSeason:(Season *)season {
if (!season) {
return NO;
}
return ((!self.season && !season.season) || self.season == season.season) &&
((!self.year && !season.year) || self.year == season.year) ;
}
@end
Использование:
Season *season2 = [Season seasonWithYear:2010 season:kFall];
Season *season3 = [Season seasonWithYear:2009 season:kFall];
[season2 isEqual:season3];