为了学习,我有一个代码我想写成块。
我有这个NSMutableArray,它是NSDictionary对象的集合。在每个字典里面都有一个与密钥“time”相关联的NSString对象。我试图找出该字典中是否存在给定时间。如果我没有使用块,我会这样做:
for( NSDictionary* obj in allTimes ) {
double aValue = [[obj objectForKey:@"time"] doubleValue];
if (time == timeX)
[self doStuff];
}
使用块......
__block BOOL found = NO;
[allTimes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
double aValue = [[obj objectForKey:@"time"] doubleValue];
NSLog(@"a value=%@", [obj objectForKey:@"time"] );
if (aValue == timeX) {
*stop = YES;
found = YES;
}
}];
但这从未发现任何事情。所有“aValue”都是零,所有[obj objectForKey:@“time”]都是空字符串。
答案 0 :(得分:1)
此代码适用于我,哪些对您不起作用?在重新创建问题时我做错了吗?
NSMutableArray *array = [NSMutableArray array];
NSDictionary *dict1 = [NSDictionary dictionaryWithObject:@"hehe" forKey:@"time"];
NSDictionary *dict2 = [NSDictionary dictionaryWithObject:@"hehe2" forKey:@"time"];
[array addObject:dict1];
[array addObject:dict2];
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
double aValue = [[obj objectForKey:@"time"] doubleValue];
NSLog(@"a value=%@", [obj objectForKey:@"time"] );
NSLog(@"aValue = %d", aValue);
}];