[英]Why NSMutableDictionary's setValue:forKey doesn't work
I want to write a timer class that records average elapsed time of a function. 我想编写一个计时器类,记录一个函数的平均经过时间。 So I want to save how many times the function is ran. 所以我想保存该函数运行了多少次。 But the item in dictionary isn't changed. 但是字典中的项目没有改变。
here is my code: 这是我的代码:
@implementation Timer {
NSDate *startTime;
// NSString *item;
NSMutableDictionary *itemCounts;
NSMutableDictionary *itemTimes;
}
- (void)tic {
startTime = [NSDate date];
}
- (void)tocWithMessage:(NSString*)message {
if (itemCounts[message] == nil) {
// itemCounts[message] = @1;
[itemCounts setValue:@1 forKey:message];
NSLog(@"%d", [itemCounts[message] integerValue]);
} else {
itemCounts[message] = @([itemCounts[message] integerValue] + 1);
}
double totalTime = [itemTimes[message] doubleValue];
double thisTime = -[startTime timeIntervalSinceNow] * 1000;
totalTime += thisTime;
itemTimes[message] = @(totalTime);
int count = [itemCounts[message] integerValue];
double averageTime = totalTime / count;
NSLog(@"%@: No.%d, average time: %lfms", message, count, averageTime);
// std::cout << message << ": " << 1. * (clock() - timerTimestamp) / CLOCKS_PER_SEC * 1000 << "ms" << std::endl;
}
@end
But the itemCounts[message] is always nil. 但是itemCounts [message]始终为零。 Please help me :) 请帮我 :)
Thanks in advance! 提前致谢!
You have only declared the dictionaries. 您只声明了字典。
Before using them you have to initialize them somewhere: 在使用它们之前,您必须在某个地方初始化它们:
itemCounts = [[NSMutableDictionary alloc] init];
itemTimes = [[NSMutableDictionary alloc] init];
You forgot to initialize the dictionaries. 您忘记了初始化字典。 In Swift you would have seen a crash if you do like this :) 在Swift中,如果您这样做的话,可能会崩溃:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.