iOS[Block-코드를 더욱 모듈화] 장면'코드 저장','메시지 전송','파라미터 사용'[봉인 도구 클래스],'반환값'[체인 프로그래밍] 사용

9002 단어

1. 코드 저장


Block: 한 방법에서 정의하고 다른 방법에서 코드 장면을 호출(상용하지 않음) 저장합니다. 코드는 모델에 저장되고tableView는cell을 클릭한 상태에서 모델의 Block 코드 보기-모델-컨트롤러를 실행합니다.단계
  • 1: tableViewController로 tableView를 관리하고 데이터 원본을 설정합니다.
  • 2: 모델 정의 Block 속성, 제목 속성, 컨트롤러에서 데이터를 가져와 모델에 값을 부여
  • 3 모델의 제목 속성은tableView의cell에 값을 부여하는 제목 속성
  • 4클릭cell에서 모델을 추출하여 Block의 값이 있는지 판단하고 실행 모델 중의 Block
  • @property (nonatomic ,strong) void(^block)();
    @property (nonatomic ,strong) NSString *title;
    
    - (void)viewDidLoad {
        [super viewDidLoad];
    
        //    
        CellItem *item = [[CellItem alloc] init];
        item.title = @"   ";
        item.block = ^{
            NSLog(@"   ");
        };
    
        //    
        CellItem *item1 = [[CellItem alloc] init];
        item1.title = @"   ";
        item1.block = ^{
            NSLog(@"   ");
        };
    
        //    
        CellItem *item2 = [[CellItem alloc] init];
        item2.title = @"   ";
        item2.block = ^{
            NSLog(@"   ");
        };
        _cellArr = @[item,item1,item2];
    }
    
    //   cell    
    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
        CellItem *item = self.cellArr[indexPath.row];
    
        if (item.block) {
            item.block();
        }
    }
    

    2. 메시지 전송값 [에이전트]//블록: 한 클래스에 정의되어 다른 클래스에 호출(상용)되어 -> 전송값


    전송: A -> B 순전: 속성 정의 B -> A 역전: 에이전트 (block 대체 에이전트)
          :   ,            
    
  • 1.이벤트 수신 대상 h에서 Block 속성 성명
  • 2.이벤트 수신 방법에서 Block 속성에 값을 부여
  • 3.이벤트 대상을 처리하는 방법에서 이벤트 대상을 수신하고 속성을 호출하며 클로즈업으로 속성 변수를 가져오고 클로즈업에서 속성 변수를 사용합니다
  • @interface ModalViewController : UIViewController
    @property (nonatomic ,strong) void(^valueBlock)(NSString *value);
    @end     //          ,             
    
    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event   //    
    {   if (_valueBlock) {  //          ,         
            _valueBlock(@"123");
        }
    }
    
    ModalViewController *modalVc = [[ModalViewController alloc] init];
        modalVc.valueBlock = ^(NSString *value){
            NSLog(@"   %@",value);
            //     ,      
        };
    

    3. 매개 변수 사용 - [봉인 도구류]

    CalculateManager *manager = [[CalculateManager alloc]init];//     
    [manager calculate:^float(float result) {//    /     
            result +=user_a_input_num;//       +    
            result *=user_b_input_num;//       *    
            return result; //      ,           ,       
        }];
    
           
    #import 
    @interface CalculateManager : NSObject
    /**      */
    @property (nonatomic, assign) float result;
    //  
    - (void)calculate:(float(^)(float result))block;
    @end
    
    #import "CalculateManager.h"
    @implementation CalculateManager
    - (void)calculate:(float (^)(float))block
    {//          
        _result = block(_result);//       [         ]-        -       [   float    ]
    }
    @end
    

    프로그램 실행 단계:
  • 1.입수 계산기
  • 2.사용자 계산기 열기/사용
  • 3.계산기가 사용자의 메시지에 응답
  • 4.계산기 계산 시작
  • 5.사용자 입력 필요
  • 6 계산기 저장 결과
  •       ,            
    /**
     *  @return       
     */
    + (instancetype)sharePublishedPassTime;
    
    /**      - passTimes_str */
    @property (nonatomic, strong) NSString *passTimes_str;
    
    /**
     *  [passTimes_str=    -    ]
     *
     *  @param str_time          
     *  @param passTimes_str        
     *
     *  @return        
     */
    
    - (NSString *)PublishedPassTimeWithTimeNSString:(NSString *)str_time result:(void(^)(NSString *passTimes_str))passTimes_str;
    
    - (NSString *)PublishedPassTimeWithTimeNSString:(NSString *)str_time result:(void(^)(NSString *passTimes_str))passTimes_str
    {
    
        //         [    ]
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyy-MM-dd HH:mm";
        //    @"yyyy-MM-dd HH:mm:ss Z";      @"2015-06-29 07:05:26 +0000";
        NSDate *date = [formatter dateFromString:str_time];
    
        //       
        NSDate *now = [NSDate date];
    
        /**        */
        NSCalendar *calendar = [NSCalendar currentCalendar];
        NSCalendarUnit type = NSCalendarUnitYear |
        NSCalendarUnitMonth |
        NSCalendarUnitDay |
        NSCalendarUnitHour |
        NSCalendarUnitMinute |
        NSCalendarUnitSecond;
        NSDateComponents *cmps = [calendar components:type fromDate:date toDate:now options:0];
    
        if (cmps.year != 0) {
            _passTimes_str = [NSString stringWithFormat:@"%ld  ",cmps.year];
        }else if (cmps.month != 0){
            _passTimes_str = [NSString stringWithFormat:@"%ld  ",cmps.month];
        }else if (cmps.day != 0){
            _passTimes_str = [NSString stringWithFormat:@"%ld  ",cmps.day];
        }else if (cmps.hour != 0){
            _passTimes_str = [NSString stringWithFormat:@"%ld   ",cmps.hour];
        }else if (cmps.hour != 0){
            _passTimes_str = [NSString stringWithFormat:@"%ld   ",cmps.minute];
        }else{
            _passTimes_str = @"  ";
        }
    
        passTimes_str(_passTimes_str);
    
        return _passTimes_str;
    }
    
    [[GLPublishedPassTime sharePublishedPassTime] PublishedPassTimeWithTimeNSString:item.create result:^(NSString *passTimes_str) {// cell       set            
            self.create.text = passTimes_str;
        }];
    
    static GLPublishedPassTime *_instance;
    /**      */
    + (instancetype)sharePublishedPassTime
    {
        return [[self alloc]init];
    }
    
    + (instancetype)allocWithZone:(struct _NSZone *)zone
    {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            _instance = [super allocWithZone:zone];
        });
        @synchronized(self) {
            if (_instance == nil) {
                _instance = [super allocWithZone:zone];
            }
        }
        return _instance;
    }
    

    프로그램 실행 단계:
  • 1.cell에서 계산 단례 대상을 획득하고 대상을 호출하는 방법
  • 2.시간차를 계산하고 조건에 따라 문자열 지정passTimes_str
  • 3.Block으로 호출하여 문자열passTimes_str는 Block 매개 변수에 전달하여 외부에 사용
  • 4.외부cell에서 매개 변수를 받아cell의 속성에 값을 부여
  • 5.cell의 클립 코드 블록 실행 완료
  • 6 공구류.대상 방법 반환 문자열
  • 4. 반환값[체인 프로그래밍]


    수요: 외부에서 계산 매개 변수만 전달하고 점 문법[속성 값 획득]을 사용하거나 [계산 수정 어떤 속성]을 사용하며 계산은 도구 클래스에 봉인됩니다.외부에서 어떻게 사용하고, 내부 공구를 어떻게 설계하는가.
    CalculateManager *mgr = [[CalculateManager alloc]init];
    NSLog(@"%d",mgr.add(5).add(5).add(5).result);
    
    #import 
    @interface CalculateManager : NSObject
    /** result */
    @property (nonatomic, assign) int result;
    - (CalculateManager *(^)(int value))add;
    @end
    
    #import "CalculateManager.h"
    @implementation CalculateManager
    -(CalculateManager *(^)(int))add
    {
        return ^(int value){
            _result +=value;
            return self;
        };
    }
    @end
    

    봉인 도구 클래스: 반환값에 Block을 정의하고 Block에 문자열 파라미터를 입력하며 계산 결과는 도구 클래스 속성에 저장합니다
    self.create.text = [GLPublishedPassTime sharePublishedPassTime].passTime(item.create).passTimes_str;
    
    /**      - passTimes_str */
    @property (nonatomic, strong) NSString *passTimes_str;
    
    /**
     *  block   str_time    ,     passTimes_str   
     */
    - (GLPublishedPassTime *(^)(NSString *str_time))passTime;
    
    - (GLPublishedPassTime *(^)(NSString *))passTime
    {
        return ^(NSString *str_time){
    
            //         [    ]
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyy-MM-dd HH:mm";
            //    @"yyyy-MM-dd HH:mm:ss Z";      @"2015-06-29 07:05:26 +0000";
            NSDate *date = [formatter dateFromString:str_time];
    
            //       
            NSDate *now = [NSDate date];
    
            /**        */
            NSCalendar *calendar = [NSCalendar currentCalendar];
            NSCalendarUnit type = NSCalendarUnitYear |
            NSCalendarUnitMonth |
            NSCalendarUnitDay |
            NSCalendarUnitHour |
            NSCalendarUnitMinute |
            NSCalendarUnitSecond;
            NSDateComponents *cmps = [calendar components:type fromDate:date toDate:now options:0];
    
            if (cmps.year != 0) {
                _passTimes_str = [NSString stringWithFormat:@"%ld  ",cmps.year];
            }else if (cmps.month != 0){
                _passTimes_str = [NSString stringWithFormat:@"%ld  ",cmps.month];
            }else if (cmps.day != 0){
                _passTimes_str = [NSString stringWithFormat:@"%ld  ",cmps.day];
            }else if (cmps.hour != 0){
                _passTimes_str = [NSString stringWithFormat:@"%ld   ",cmps.hour];
            }else if (cmps.hour != 0){
                _passTimes_str = [NSString stringWithFormat:@"%ld   ",cmps.minute];
            }else{
                _passTimes_str = @"  ";
            }
            return self;
        };
    }
    
    /**      */
    + (instancetype)sharePublishedPassTime
    {
        return [[self alloc]init];
    }
    

    마지막으로 요약: Block이 개발에서 가장 긴 것은 두 번째입니다 .세 번째와 네 번째 사용 장면에 대해 처리해야 할 방법으로 많이 사용한다.위와 같이 되돌아오는 값이 필요할 뿐입니다. 사용자 정의 도구 클래스 중 하나의 클래스 방법으로 해결할 수 있습니다.

    마지막으로 모두 건강하세요.안녕히 계십시오.

    좋은 웹페이지 즐겨찾기