访问奇怪的Objective-C块中的值

时间:2014-05-28 09:52:37

标签: objective-c objective-c-blocks

我有一个非常奇怪的测试任务。在头文件中有一个函数:

NSString *AppendString(NSString *string, void (^block)(NSString *stringToAppend));

它应该使用块将一个字符串附加到另一个字符串。在我看来,我应该这样运行:

NSString *newString = AppendString(@"firstString", ^(NSString *stringToAppend){
    stringToAppend = @"secondString";
});

如何实现此功能?我不知道如何处理C风格的功能块。禁止以Objective-C样式重新编写基本功能。感谢您的帮助,对不起我的英语。

编辑:

声明:

NSString *AppendString(NSString *string, void (^block)(NSString *stringToAppend));

实施(不确定):

NSString *AppendString(NSString *string, void (^block)(NSString *stringToAppend)){
    // Logic should be here
    // No idea how to access to block variables here
    // I need to concatenate string and stringToAppend(string+stringToAppend)
    return *Result of calculation(NSString*)*
}

使用:

NSString *newString = AppendString(@"firstString", ^(NSString *stringToAppend){
    // no logic here, just block parameter assignment
    // is it possible to assign stringToAppend here and access to it's variable inside using?
    stringToAppend = @"secondString";
});

如何写出正确的实现?

1 个答案:

答案 0 :(得分:1)

此函数在块内传递NSString,因此您需要保存该字符串而不分配给它:

// Declare new block variable (you can assign data to it inside block) to save string
__block NSString *newString = @"";

AppendString(@"firstString", ^(NSString *stringToAppend){
    // Save variable returned by block in variable defined above
    newString = stringToAppend;
});
// Log result to the console
NSLog(@"Result: %@", newString);

// EDITED

//1. Declaration
// (^block) - this define name of your block, in this case the name is - block
// You don't have to use NSString the data is returned by block, not function
void AppendString(NSString *string, void (^block)(NSString *stringToAppend));

//1. Implementation function doesn't return the data, the data is returned by block:
void AppendString(NSString *string, void (^block)(NSString *stringToAppend)){
    block(string);
}

//1.Using:
__block NSString *result = @"";

    AppendString(@"test", ^(NSString *stringToAppend) {
        result = stringToAppend;
    });
    NSLog(@"Result: %@", result);


//2. Declaration
// You return the data by function and by block
NSString* AppendString(NSString *string, void (^block)(NSString *stringToAppend));

//2. Implementation function returns the data, and block too:
NSString* AppendString(NSString *string, void (^block)(NSString *stringToAppend)){
    block(string);
    return [NSString stringWithFormat:@"%@ - returned by function", string];
}
//2.Using:
__block NSString *result = @"";

    NSString *funcResult =  AppendString(@"test", ^(NSString *stringToAppend) {
        result = stringToAppend;
    });
    NSLog(@"Block result: %@", result);
    NSLog(@"Function result: %@", funcResult);

有两个示例可以创建和使用您想要的功能。 看看两者,评论应该解释它们的工作原理。