2013-04-11 2 views
0

블록 사용에 관해 많은 긍정적 인 점을 읽었습니다. 특히 델리게이트 호출을 제거하여 코드를 단순화했습니다. 대리자 호출 대신에 블록이 애니메이션 끝 부분에서 사용되는 예제를 발견했습니다. 블록 예 쉽지만 난 대리인 사용 예 app.for 아이폰 예를 사용할 수블록을 사용하여 델리게이트 값으로 바꾸기

.H

@protocol AWActionSheetDelegate <NSObject> 

- (int)numberOfItemsInActionSheet; 
- (AWActionSheetCell*)cellForActionAtIndex:(NSInteger)index; 
- (void)DidTapOnItemAtIndex:(NSInteger)index; 

@end 

@interface AWActionSheet : UIActionSheet 

    @property (nonatomic, assign)id<AWActionSheetDelegate> IconDelegate; 
-(id)initwithIconSheetDelegate:(id<AWActionSheetDelegate>)delegate ItemCount:(int)cout; 
@end 

하는 .m

- (void)actionForItem:(UITapGestureRecognizer*)recongizer 
{ 

    [IconDelegate DidTapOnItemAtIndex:cell.index]; 

} 

및 그것을 사용

-(void)DidTapOnItemAtIndex:(NSInteger)index 
{ 
    NSLog(@"tap on %d",index); 

} 

어떻게 블록을 사용하지 마십시오. 색인을 얻을 수 있습니까? 조언을 해주고 좋은 블록 카테고리를 제공 할 수 있습니까? 효과를 마무리 매우 좋습니다. 내가 인덱스를 전달하는 대리자를 사용하려면이 donot, 난 단지 인덱스

+0

무엇을 완료 하시겠습니까 ?? 더 자세히 설명해 주시겠습니까 ?? – TheTiger

+0

내 english.my 코드에 대한 죄송합니다 대리인을 사용하고 있습니다, 나는 같은 효과를 완료하기 위해 블록을 사용하고 싶습니다 – pengwang

+0

그리고 대리인과 블록 모두 다른 작업을 ... – TheTiger

답변

1

난 당신이 이런 식으로 뭔가를 찾고 생각 얻을 블록을 사용하려면 :

//implementation for AWActionSheet's method: actionForItem:withBlock: 

-(void) actionForItem:(UITapGestureRecognizer*)recongizer withBlock:(void(^)(NSInteger integer)) block { 

    NSInteger myInt = 0; 
    //whatever 

    //callback 
    block(myInt); 
} 

하고 통화를

AWActionSheet* actionSheet; 
[actionsheet actionForItem:recognizer withBlock:^(NSInteger integer) { 
    NSLog(@"myInt: %d", integer); 
}]; 
+0

대리인 대신 일어날 수 있습니까 ?? 어떤 작업이 우리가 델리게이트와 알림을 사용하여 할 수있는 것과 같이 수행 할 때 어떻게 한 클래스가 다른 클래스를 호출 할 것인가? 내가 알고 싶습니다 – TheTiger

+0

질문을 이해하는 데 어려움을 겪고 있습니다. 대의원을 대신해서는 안됩니다. 이 코드를 사용하면 object1에서 object2의 메소드를 실행할 수 있으며 object2의 매개 변수를 전달하는 object1의 다른 메소드 (콜백)를 호출하면 완료 할 수 있습니다. – Odrakir

+0

그래, 내가 정확히 @penwang에게 말하고 싶은 것이 있지만 .... 그가 얻지 못하고있다. BTW 나는 그것을 묻지 않았다 :) 어떤 방법 으로든 고마워한다. – TheTiger

0

사용이 객체 :

https://github.com/matteogobbi/MGActionSheet

이 쉬운 예를 들어 초기화하고 블록 단위로 객체를 사용하십시오 :

//Initialization 
MGActionSheet *actionSheet = [[MGActionSheet alloc] initWithTitle:@"Block action sheet!" cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"Delete" otherButtonTitles:@"Option 1", @"Option 2", @"Option 3", nil]; 

//Show with completition block 
[actionSheet showInView:self.view withChoiceCompletition:^(int buttonIndex) { 

    if(buttonIndex == actionSheet.cancelButtonIndex) NSLog(@"Cancelled"); 
    else if(buttonIndex == actionSheet.destructiveButtonIndex) NSLog(@"Destructed"); 
    else { 
     NSLog(@"Option at index: %d", buttonIndex); 
    } 
}];