【发布时间】:2017-02-11 10:02:18
【问题描述】:
我正在使用 MagicalRecord 和 CoreData Wrapper 在我的应用程序中实现最喜欢的场景。我正在搜索如果在我的实体中找到该属性的值,它会将其作为 fav 删除,否则会将其添加到 fav。在此处执行DX *foundDX = [DX MR_findFirstByAttribute:@"code" withValue:cell.DXCodeName.text]; foundDX 是我正在检查的值。
我已将 UISearchBar 添加到我的 tableView 中。因此,当视图被加载时,它会显示已经收藏的项目,这些项目使用可以取消收藏。如果用户搜索并选择一个项目,它成功地将其添加到收藏夹并成功地将其从数据模型中删除。但如果我再次点击收藏按钮,它就会崩溃。
if (!foundDX.code) {
//If we are always getting into here that means that either foundDX is nil
//or the code is nil so you need to verify the logic around that.
if (indexPath != nil)
{
if (!_AddEditDX) {
self.AddEditDX = [DX MR_createEntity];
}
[self.AddEditDX setCode:cell.DXCodeName.text];
[self.AddEditDX setDescriptions:cell.DXDescText.text];
[self.AddEditDX setIsFav:[NSNumber numberWithInt:1]];
[[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
[self.favDXArray addObject:self.AddEditDX];
[self fetchFavDX];
[cell.DXFavButton setImage:[UIImage imageNamed:@"star_filled"] forState:UIControlStateNormal];
[KSToastView ks_showToast:@"Added to Favourite" duration:1.0f];
}
} else if(self.favDXArray.count > indexPath.row) {
//You can get rid of the if(foundDX.code) because this is the else block to not having it so we must have it.
//Only thing to worry about is the array size
NSLog(@"count is: %ld and row is: %ld",_favDXArray.count, (long)indexPath.row);
DX *tempDX = [self.favDXArray objectAtIndex:indexPath.row];
[tempDX MR_deleteEntity];
[cell.DXFavButton setImage:[UIImage imageNamed:@"star_blank"] forState:UIControlStateNormal];
[self.favDXArray removeObjectAtIndex:indexPath.row];
[[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
[KSToastView ks_showToast:@"Removed from Favourite" duration:1.0f];
}
通过应用一些断点我发现:
假设代码是E45 和foundDX 第一次没有找到并添加到数据模型中。然后再次按下 fav 按钮将其删除,实际上它确实删除了它。但是,如果我再次点击 fav 按钮,foundDX 仍然是E45,因此它崩溃了。但如果我关闭应用程序并再次运行它,E45 将不再存在。
更新
我已经更新了上面的代码。我在viewDidLoad 中使用了fetchFavDX,所以我尝试在上面代码中更新的方法中调用它。而在fetchFavDX 我正在这样做:
-(void)fetchFavDX {
self.favDXArray = [NSMutableArray arrayWithArray:[DX MR_findAllSortedBy:@"code" ascending:YES]];
}
现在它在前两次工作正常意味着添加/删除/添加/删除。之后它只运行 if (!foundDX.code) 块,这意味着它不会进入 else 部分。
【问题讨论】:
-
你能用崩溃日志更新上面的内容吗?请
-
@HarmVanRisk 它是
index 0 beyond bounds for empty array',表示对象已被删除,如果我再次运行该应用程序,这是正确的。但如果它是相同的运行,它会因此错误而崩溃。
标签: ios objective-c core-data magicalrecord