相关疑难解决方法(0)

将对象分配给块外的变量

以下代码崩溃,因为sentence当最后一个块退出时内容消失.

#import <Foundation/Foundation.h>    
int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    // simple block test - just iterate over some items and 
    // add them to a string
    NSArray *items = [NSArray arrayWithObjects:@"why ", @"must ", @"this ",nil];
    __block NSString *sentence = @"";   
    [items enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
    {
        sentence = [sentence stringByAppendingFormat:@"%@",obj];
    }];
    // crash!
    NSLog(@"Sentence is %@",sentence);
    [pool drain];
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

使这项工作的正确/惯用方法是什么?

objective-c objective-c-blocks

8
推荐指数
1
解决办法
3926
查看次数

标签 统计

objective-c ×1

objective-c-blocks ×1