iphone - block not working as expected
I have a code that I am trying to write as block, for the sake of learning.
I have this NSMutableArray that is a collection of NSDictionary objects. Inside each dictionary there's a NSString object associated to the key "time". I am trying to find if a given time is present on that dictionary. If I was not using blocks I would do this:
for( NSDictionary* obj in allTimes ) {
double aValue = [[obj objectForKey:@"time"] doubleValue];
if (time == timeX)
[self doStuff];
}
using blocks...
__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;
}
}];
but t开发者_JAVA百科his is never founding anything. All "aValue" are coming as zero and all [obj objectForKey:@"time"] are coming as empty strings.
This code works for me, what doesn't work for you? Did I do something wrong when recreating your problem?
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);
}];
精彩评论