2009-02-27 78 views
0

我有一個包含對象集合的類。我正在嘗試創建一個方法,該方法將返回匹配提供的謂詞的集合的第一個成員。無法識別的選擇器,但調試可以看到它

以下是採集方法:

... 
//predicate is a boolean method that accepts an object as its single parameter 
-(id<Notation>) getFirstChildMatching: (SEL) predicate declaredInInstance:(id) instance 
{ 
    NSMethodSignature *sig = [[instance class] instanceMethodSignatureForSelector:predicate]; 
    NSInvocation *myInvocation = [NSInvocation invocationWithMethodSignature:sig]; 
    [myInvocation setTarget:instance]; 
    [myInvocation setSelector:predicate]; 

    int numItems = childNotations.count; 
    for(int i=0;i< numItems;i++) 
    { 
     id<Notation> thisNotation = [childNotations objectAtIndex:i]; 
     [myInvocation setArgument:thisNotation atIndex:2]; 
     BOOL result =NO; 
     [myInvocation retainArguments]; 
     [myInvocation invoke]; 
     [myInvocation getReturnValue:&result]; 

     if (result) 
      return thisNotation; 

    } 

    return nil; 
} 

我創建了一個測試類,測試這種方法。 下面是測試方法加上謂詞:

- (void) testGetFirstChildMatching 
{ 
    Leaf *line1 = [[Leaf alloc] initWithValue:1 step:Step_A andNumber:1]; 
    Leaf *line2 = [[Leaf alloc] initWithValue:2 step:Step_B andNumber:2]; 

    SEL mySelector = @selector(valueIs1:); 

    id<CompositeNotation> compositeNotation = [[CompositeNotation alloc] init]; 
    [compositeNotation addNotation:line1]; 
    [compositeNotation addNotation:line2]; 

    id notation = [compositeNotation getFirstChildMatching: mySelector declaredInInstance:self]; 
    STAssertEquals(YES, [notation isKindOfClass:[Leaf class]], @"Should be of type Leaf: %@", notation); 
    //Leaf *found = ((Leaf *)notation); 
    STAssertEquals([notation value], line1.value, @"Should have found line 1 with value 1: actual %i", [notation value]); 
    [line1 release]; 
    [line2 release]; 
} 

-(BOOL) valueIs1: (Leaf *) leaf 
{ 
    if (leaf.value == 1) 
     return YES; 

    return NO; 
} 

我所發現的是,在「如果(leaf.value == 1)」行,我得到一個「無法識別的選擇發送到類」。沒有意義的是,調試器可以看到value屬性和它的值,所以對象顯然具有該選擇。 任何想法?

順便說一句葉實現符號協議

回答

1

我最終發現了這個問題。 正是這條線

[myInvocation setArgument:thisNotation atIndex:2]; 

它應該是

[myInvocation setArgument:&thisNotation atIndex:2]; 

感謝

3

錯字在函數定義?

-(BOOL) valueIs1: (Leaf *) Leaf // <== should be "leaf" not "Leaf" ? 

你得到的事實「無法識別的選擇發送到班」,沒有實例,意味着leafClass。兩件事要檢查:

  • 確保Leaf的初始化程序initWithValue正在返回一個對象。
  • 確保addNotation:正確地將葉子添加到陣列。
+0

選購不易混淆的變量命名策略很好的理由。 – danielpunkass 2009-02-27 17:06:42

相關問題