Objective-CクラスがFactorHelper
と定義されています。それはNSMutableArray
のNSNumbers
の要因と呼ばれる特性を持っています。 2つのFactorHelper
オブジェクトのfactorプロパティが同じ番号を持つ場合(たとえ数値が異なる順序であっても)、trueを返すこのクラスのカスタムisEqual:
メソッドがあります。* [NSMutableSet addObject:X] *既に[セット]内にあるオブジェクトYに対して* [Y isEqual:X] *がTRUEを返す場合でもオブジェクトXを追加します
私は2つのFactorHelper
オブジェクト10,2,5と10,5,2有するものとその他を作成することにより、テストしようとしました。次に、NSMutableSet
を作成し、firstObjectを追加してから2番目のオブジェクトを追加しました。 2番目のオブジェクトが追加されないことを期待していましたが、追加されています。コードをステップ実行すると、isEqual
がaddObjectによって呼び出され、TRUE
が返されています。私は間違って何をしていますか? [NSMutableSet alloc] init]
に[NSMutableSet new]
を変更
UPDATE
は期待通りに物事が動作します。
また、すべてのTRUEを変更するとFALSEはisEqualがYESになり、NOは正しく動作します([NSMutableSet new]
として保持しても)。
私は何が起こっているのか分かりません。誰かが光を放つことができますか?
クラス定義
@interface FactorHelper: NSObject
@property NSMutableArray <NSNumber *> *factors;
-(BOOL) isEqual:(FactorHelper *)other;
-(instancetype) initWithFactors:(NSMutableArray *)factors;
-(NSString *) description;
@end
@implementation FactorHelper
- (instancetype) initWithFactors:(NSMutableArray *)factors
{
self = [super init];
if (self) {
_factors = factors;
}
return self;
}
-(BOOL) isEqual:(FactorHelper *)other
{
if ([self.factors count] != [other.factors count])
{
return FALSE;
}
else
{
NSMutableDictionary <NSNumber *, NSNumber *> *myHashTable = [[NSMutableDictionary alloc] init];
for (NSNumber *nextNumber in self.factors) {
if(myHashTable[nextNumber] == nil)
{
myHashTable[nextNumber] = @(1);
}
else
{
myHashTable[nextNumber] = @([myHashTable[nextNumber] integerValue]+1);
}
}
for (NSNumber *nextNumber in other.factors)
{
if(myHashTable[nextNumber] == nil)
{
return FALSE;
}
else
{
myHashTable[nextNumber] = @([myHashTable[nextNumber] integerValue] - 1);
if ([myHashTable[nextNumber] integerValue] == 0) {
[myHashTable removeObjectForKey:nextNumber];
}
}
}
if ([[myHashTable allKeys] count] == 0)
{
return TRUE;
}
else
{
return FALSE;
}
}
}
@end
ユニットテストコード
NSMutableSet *testSet = [NSMutableSet new];
FactorHelper *fact1 = [[FactorHelper alloc] initWithFactors:[@[@(10),@(5),@(2)] mutableCopy]];
FactorHelper *fact2 = [[FactorHelper alloc] initWithFactors:[@[@(10),@(2),@(5)] mutableCopy]];
[testSet addObject:fact1];
[testSet addObject:fact2];
NSLog(@"Are factors 1 and 2 the same: %d",[fact1 isEqual:fact2]);
あなたのコードでは、NSMutableSetを使用していますか? – Willeke
testSetはNSMutableSetです。上記のメインコードに追加されました。このコードは、OS Xのコマンドラインツールのメインメソッドの中にあります。下の私の答えを見てください。すべてのTRUE/FALSEをYES/NOに変更すると、問題が修正されました。 –