iOS 利用Block實現鏈式編程

來源:互聯網
上載者:User

標籤:

1. 傳統編程

// Person的方法

- (void)eat

{

    NSLog(@"吃飯");

}

 - (void)learn

{

    NSLog(@"學習");

}

- (void)play

{

    NSLog(@"娛樂");

}

 

// 連續做事情

Person *p = [ [Person alloc] init ];

[p eat];

[p learn];

[p play];

 

2. 不用Block,實現鏈式編程

// Person的方法

- (Person *)eat

{

    NSLog(@"吃飯");

   return self;

}

 - (Person *)learn

{

    NSLog(@"學習");

    return self;

}

- (Person *)play

{

    NSLog(@"娛樂");

    return self;

}

// 連續做事情,這麼寫看得眼花 

Person *p = [ [Person alloc] init ];

[[[p eat] learn] play];

 

3. 利用Block實現鏈式編程

// Person的方法

- ( Person *(^)() )eat

{

  return ^{

        NSLog(@"吃飯");

      return self;

  };

}

- ( Person *(^)() )learn

{

  return ^{

        NSLog(@"學習");

      return self;

  };

}

- ( Person *(^)() )play

{

  return ^{

        NSLog(@"娛樂");

      return self;

  };

}

// 連續做事情

Person *p = [ [Person alloc] init ];

p.eat().learn().play();

 

4. 帶參數的鏈式編程

比如人的吃飯方法,參數是 NSString *food

- ( Person *(^)() )eat:(NSString*) food

{

  return ^(food){

        NSLog(@"吃飯);

      return self;

  };

}

如果是上面這種寫法:p.eat後面不能跟 :food, 因為p.eat本身就等同於[ p eat:(NSString *)food ],如果寫p.eat:food ,相當於 [p eat::food],這樣是不對的.

所以正確的寫法:

- ( Person *(^)( NSString* food ) )eat

{

  return ^( NSString* food ){

        NSLog(@"吃飯---- %@",food);

      return self;

  };

}

// 連續做事情

p.eat(@"白菜").learn().play();

 

5. 總結,用Block實現鏈式編程無非就是:方法的傳回值是一個Block,Block內部裝著真正要執行的方法,Block內部再返回self;     如果有參數,通過Block的參數往裡傳.

- ( 傳回值是Block ) 方法名

{

    return *{

      Block內部裝著真正要執行的代碼

      return self;

    };

}

 

iOS 利用Block實現鏈式編程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.