소의 블락.

7833 단어 block

하나.역할


기능은 함수와 비슷하여 사용할 때 정의하여 코드의 작용을 명확하게 할 수 있다.블록에서 글로벌 변수, 정적 변수, 수정 가능block 수식의 국부 변수입니다.
예1: 선언 실현
int (^Multiply)(int, int) = ^(int num1, int num2) {
    return num1 * num2;
};

int result = Multiply(7, 4); // result is 28

  
예2: 호출 대비
- (void)viewDidLoad {
   [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self
        selector:@selector(keyboardWillShow:)
        name:UIKeyboardWillShowNotification object:nil];
}

- (void)keyboardWillShow:(NSNotification *)notification {
    // Notification-handling code goes here.
}

With the addObserverForName:object:queue:usingBlock: method you can consolidate the notification-handling code with the method invocation:
- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserverForName:UIKeyboardWillShowNotification
         object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *notif) {
             // Notification-handling code goes here. 
    }];
}

  

둘.시스템 API에서의 사용


1.Completion handlers
2.Error handlers
리셋 함수에 해당하며, 완성할 때 시작할 때 오류가 발생할 때 어떤 방법을 사용합니까?
Listing 1-1  A completion-handler block
- (IBAction)animateView:(id)sender {
    CGRect cacheFrame = self.imageView.frame;
    [UIView animateWithDuration:1.5 animations:^{
        CGRect newFrame = self.imageView.frame;
        newFrame.origin.y = newFrame.origin.y + 150.0;
        self.imageView.frame = newFrame;
        self.imageView.alpha = 0.2;
    }
                     completion:^ (BOOL finished) {
                         if (finished) {
                             // Revert image view to original.
                             sleep(3);
                             self.imageView.frame = cacheFrame;
                             self.imageView.alpha = 1.0;
                         }
                     }];
}

  
3.Notification handlers
이벤트를 등록하는 또 다른 방법.
As with notification-handler methods, an NSNotification object is passed in. The method also takes an NSOperationQueue instance, so your application can specify an execution context on which to run the block handler.
 
Listing 1-2  Adding an object as an observer and handling a notification using a block
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    opQ = [[NSOperationQueue alloc] init];
    [[NSNotificationCenter defaultCenter] addObserverForName:@"CustomOperationCompleted"
             object:nil queue:opQ
        usingBlock:^(NSNotification *notif) {
        NSNumber *theNum = [notif.userInfo objectForKey:@"NumberOfItemsProcessed"];
        NSLog(@"Number of items processed: %i", [theNum intValue]);
    }];
}

  
4.Enumeration
누적기를 지원하는 NSArray, NSDictionary, NSSet, NSIndexSet의 경우 두 가지 형태의 Blocks가 있습니다.하나는 값을 되돌려주지 않는 처리형이고, 하나는 성형을 되돌려주는 필터형이다.두 가지 매개 변수 중 bool형이 있는데 YES로 설정되었을 때, 스트리밍합니다.
Listing 1-3  Processing enumerated arrays using two blocks
NSString *area = @"Europe";
NSArray *timeZoneNames = [NSTimeZone knownTimeZoneNames];
NSMutableArray *areaArray = [NSMutableArray arrayWithCapacity:1];
NSIndexSet *areaIndexes = [timeZoneNames indexesOfObjectsWithOptions:NSEnumerationConcurrent
                                passingTest:^(id obj, NSUInteger idx, BOOL *stop) {
    NSString  *tmpStr = (NSString *)obj;
    return [tmpStr hasPrefix:area];
}];


NSArray *tmpArray = [timeZoneNames objectsAtIndexes:areaIndexes];
[tmpArray enumerateObjectsWithOptions:NSEnumerationConcurrent|NSEnumerationReverse
                           usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                               [areaArray addObject:[obj substringFromIndex:[area length]+1]];
}];

NSLog(@"Cities in %@ time zone:%@", area, areaArray);

NSString 클래스에는 두 가지 Blocks 방법이 있습니다: enumerate Substrings InRange: options: using Block: and enumerate Lines Using Block:.첫 번째는 당신이 설정한 옵션에 따라 특정 구역에 접근하는 문자열을 분할하고, 두 번째는 줄에 따라 분할합니다.
 
Listing 1-4  Using a block to find matching substrings in a string
NSString *musician = @"Beatles";
NSString *musicDates = [NSString stringWithContentsOfFile:
    @"/usr/share/calendar/calendar.music"
    encoding:NSASCIIStringEncoding error:NULL];
[musicDates enumerateSubstringsInRange:NSMakeRange(0, [musicDates length]-1)
    options:NSStringEnumerationByLines
    usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
           NSRange found = [substring rangeOfString:musician];
           if (found.location != NSNotFound) {
                NSLog(@"%@", substring);
           }
      }];

//-------the same
[musicDates enumerateLinesUsingBlock:^(NSString *line,BOOL *stop)
     {
         NSRange found = [line rangeOfString:musician];
         if (found.location != NSNotFound) {
             NSLog(@"%@", line);
         }
     }];

  
5.View animation and transitions
두 가지: 뷰 속성 및 애니메이션 끝 콜백을 변경합니다(모두 필요한 것은 아닙니다).
 
Listing 1-5  Simple animation of a view using blocks
[UIView animateWithDuration:0.2 animations:^{
        view.alpha = 0.0;
    } completion:^(BOOL finished){
        [view removeFromSuperview];
    }];

  
두 장면 전환(transitionWithView:duration:options:animations:completion:) 다음 예는 flip-left 애니메이션과 유사합니다.
Listing 1-6  Implementing a flip transition between two views
[UIView transitionWithView:containerView duration:0.2
                   options:UIViewAnimationOptionTransitionFlipFromLeft                  animations:^{
                    [fromView removeFromSuperview];
                    [containerView addSubview:toView]
                }
                completion:NULL];

  
6.Sorting
NSSortDescriptor, NSArray, and NSDictionary의 두 객체 크기를 비교합니다.
typedef NSComparisonResult (^NSComparator)(id obj1, id obj2);
Listing 1-7  Sorting an array using an NSComparator block
NSArray *stringsArray = [NSArray arrayWithObjects:
                                 @"string 1",
                                 @"String 21",
                                 @"string 12",
                                 @"String 11",
                                 @"String 02", nil];
static NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch | NSNumericSearch |
        NSWidthInsensitiveSearch | NSForcedOrderingSearch;
NSLocale *currentLocale = [NSLocale currentLocale];
NSComparator finderSort = ^(id string1, id string2) {
    NSRange string1Range = NSMakeRange(0, [string1 length]);
    return [string1 compare:string2 options:comparisonOptions range:string1Range locale:currentLocale];
};

NSLog(@"finderSort: %@", [stringsArray sortedArrayUsingComparator:finderSort]);

  
 
셋.Blocks와 동시 사용
GCD(Grand Central Dispatch) and the NSOperationQueue 클래스에서 사용
참조:https://developer.apple.com/library/ios/#featuredarticles/Short_Practical_Guide_Blocks/_index.html

좋은 웹페이지 즐겨찾기