我的代码有一个非常奇怪的错误。我有一个方法可以将消息保存到Parse.com。如果消息保存,我想运行一个增加计数器并返回BOOL的方法:[self canIncrementMessageCountForUser:tempName];
。代码如下:
[message saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if(succeeded) {
PFRelation *receivedMessages = [messageBank relationForKey:@"receivedMessages"];
[receivedMessages addObject:message];
[self canIncrementMessageCountForUser:tempName];
[messageBank saveInBackground];
NSLog(@"message send to %@",tempName);
}
}];//end block, this works
由于某些原因,未调用行[self canIncrementMessageCountForUser:tempName];
之后的任何内容。我不知道为什么。这让我很生气。 canIncrementMessageCountForUser再次返回一个bool。任何想法在这里发生了什么?
编辑:为增量方法添加了代码:
-(BOOL)canIncrementMessageCountForUser: (NSString *)user {
//erase the dictionary if it's a new day
[self flushDictionaryIfNeeded];
//load up a dictionary
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *dictionary = [defaults objectForKey:@"uniqueSentToday"];
NSLog(@"%@", [dictionary allKeys]);
//if empty it's a yes
if([dictionary count]==0){
NSLog(@"empty dictionary");
NSLog(@"First message for %@ today!",user);
NSDate *now = [NSDate date];
[dictionary setObject:now forKey:user];
[defaults setObject:dictionary forKey:@"uniqueSentToday"];
[defaults synchronize];
return YES;
}
//if it's not empty it's only a yes if the key doesn't exist
else {
//not in dict so unique
if(![dictionary objectForKey:user]){
NSLog(@"username we are checking is: %@",user);
NSLog(@"First message for %@ today!",user);
NSDate *now = [NSDate date];
[dictionary setObject:now forKey:user];
[defaults setObject:dictionary forKey:@"uniqueSentToday"];
[defaults synchronize];
return YES;
}
else {
NSLog(@"Already messaged %@ today!",user);
return NO;
}
}
}
基本上,如果今天通过检查密钥(与传入的用户字符串相同)未向用户发送消息,则此方法返回true。
答案 0 :(得分:0)
想要发布此内容,其他人认为它很有用。我想出了这个问题所在的问题:
//load up a dictionary
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *dictionary = [defaults objectForKey:@"uniqueSentToday"];
NSLog(@"%@", [dictionary allKeys]);
需要 NSMutableDictionary * dictionary = [[defaults objectForKey:@“uniqueSentToday”] mutableCopy]; 。即使您可以将可变对象写入NSUserDefaults,如果该对象被读出,它将是不可变的,因此需要调用mutableCopy。否则它会卡在 [字典setObject:now forKey:user]; 上,而不会执行其后的任何其他行。现在工作正常。我想知道为什么它会完全停留在那一行而不执行任何其他想到的行或抛出编译器错误..