Passing blocks in Objective-C

前端 未结 4 1779
青春惊慌失措
青春惊慌失措 2020-12-24 15:20

When writing a method that accepts a block as an argument, do I need to do anything special such as copying the block to the heap before executing it? For example, if I had

4条回答
  •  轮回少年
    2020-12-24 16:23

    This all looks good. Though, you might want to double-check the block parameter:

    @property id myObject;
    @property (copy) void (^myBlock)(NSString *);
    

    ....

    - (void)testWithBlock: (void (^)(NSString *))block
    {
        NSString *testString = @"Test";
        if (block)
        {
            block(test);
            myObject = Block_copy(block);
            myBlock = block;
        }
    }
    

    ...

    [object testWithBlock: ^(NSString *test)
    {
        NSLog(@"[%@]", test);
    }];
    

    Should be fine. And I believe that they are even trying to phase out Block_copy(), but they haven't yet.

提交回复
热议问题