我试图将NSString转换为NSDate
NSString destructString是2015-01-04 08:36:42 +0000
我知道问题始于我在下面评论过的地方,但我似乎无法找到问题所在。
程序在此时停止并在标题中给出错误。
代码的要点是比较两个日期以查看哪个日期较旧。
PFQuery *query = [PFQuery queryWithClassName:self.parseClassName];
NSDate *today = [[NSDate alloc]init];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if(!error){
for(PFObject* object in [self objects]){
NSLog(@"OBJECT: %@", object);
PAWPost *post = [[PAWPost alloc] initWithPFObject:object];
NSLog(@"post: %@", post);
NSLog(@"today: %@", today);
NSString *destructString = [post.object objectForKey:selfDestructDateKey];
NSLog(@"destruct string: %@", destructString);
NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss zz"];
//SOURCE OF PROBLEM BEGINS HERE
NSDate *destructDate = [dateFormat dateFromString:destructString];
NSLog(@"destruct date: %@", destructDate);
if([destructDate compare:today] == NSOrderedDescending){
[object deleteEventually];
NSLog(@"DESCENDING");
}
else
NSLog(@"NOT DESCENDING");
}
}else {
NSLog(@"Error in findObjectsInBackgroundWithBlock for destruct purposes");
}
}];
我也知道有关于此主题的另一篇文章,但我已经尝试过修复(重做格式化),但它没有解决问题。提前致谢!
答案 0 :(得分:1)
如果对象的类型可能不同,您应该添加类型检查,因为我添加到您的代码
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if(!error){
for(PFObject* object in [self objects]){
NSLog(@"OBJECT: %@", object);
PAWPost *post = [[PAWPost alloc] initWithPFObject:object];
NSLog(@"post: %@", post);
NSLog(@"today: %@", today);
id destructString = [post.object objectForKey:selfDestructDateKey];
NSLog(@"destruct string: %@", destructString);
if ([destructString isKindOfClass:[NSDate class]]) { // already date
NSDate * destructDate = (NSDate *)destructString;
} else { // parse string
NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss zz"];
//SOURCE OF PROBLEM BEGINS HERE
NSDate *destructDate = [dateFormat dateFromString:destructString];
NSLog(@"destruct date: %@", destructDate);
if([destructDate compare:today] == NSOrderedDescending){
[object deleteEventually];
NSLog(@"DESCENDING");
}
else
NSLog(@"NOT DESCENDING");
}
}
}else {
NSLog(@"Error in findObjectsInBackgroundWithBlock for destruct purposes");
}
}];