我想使用__block變量來獲取塊中的值。但是,如果塊外,__block變量似乎是零。爲什麼會發生?「__block」變量在跳出塊時導致零值
NSString *fileName = [Tools MD5Encode:url];
__block NSString *filePath = nil;
[fileList enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSString *aFileName = obj;
if ([aFileName isEqualToString:fileName]) {
NSString *path = [VERSIONS_INFO_DATA_DIRECTORY stringByAppendingPathComponent:aFileName];
filePath = path;
NSLog(@"filePath1 %@", filePath);
*stop = YES;
}
}];
//NSLog(@"filePath2 %@", filePath);
//filePath seems to be nil
return filePath;
當我將代碼更改爲[路徑複製]時,它工作。但我不知道這是否是一個好主意。任何決定?
NSString *fileName = [Tools MD5Encode:url];
__block NSString *filePath = nil;
[fileList enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSString *aFileName = obj;
if ([aFileName isEqualToString:fileName]) {
NSString *path = [VERSIONS_INFO_DATA_DIRECTORY stringByAppendingPathComponent:aFileName];
filePath = [path copy];
NSLog(@"filePath1 %@", filePath);
*stop = YES;
}
}];
//NSLog(@"filePath2 %@", filePath);
return [filePath autorelease];
這樣的情況讓我很高興我的團隊決定接受ARC。 – 2012-04-23 03:47:57