iOS development-Callback with block implementation

Source: Internet
Author: User

Callbacks are often used in iOS development, and the following describes how to implement callbacks with block.

1 #import <Foundation/Foundation.h>23@interface  block:nsobject 4 5 + (void) Getblock: (void (^) (NSString *)) Someblock; 6 7 @end
BLock.h
1 #import "BLock.h"2 #import<Foundation/Foundation.h>3 4 @implementationBLock5 6+ (void) Getblock: (void(^) (NSString *)) Someblock7 {8NSLog (@"we is in a getblock function");9Someblock (@"BLOCK Go Go");Ten } One @end
BLOCK.M

There is a block class with a static method that callbacks a string data via Someblock.

1 #import<Foundation/Foundation.h>2 #import "BLock.h"3 intMainintargcConst Char*argv[])4 {5 6 @autoreleasepool {7         8[BLock getblock:^ (NSString *str) {NSLog (@"%@", str);}];9     }Ten     return 0; One}
main.m

The str parameter returned by the callback is displayed in main.

The output is as follows

from £º31.065 myfirstapp[2430:303   in a getblock function-01 :31.066 myfirstapp[2430:3030

You can also rewrite the BLock.h and block.m files as follows:

1 #import <Foundation/Foundation.h>23 typedef  void (^ablock) (NSString *); // define a block as a new type 4 5 @interface Block:nsobject 6 7 + (void) Getblock: (Ablock) Someblock; 8 9 @end
BLock.h
1 #import "BLock.h"2 #import<Foundation/Foundation.h>3 4 5 @implementationBLock6 7+ (void) Getblock: (ablock) Someblock8 {9NSLog (@"we is in a getblock function");TenSomeblock (@"BLOCK Go Go"); One } A @end
BLOCK.M

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.