将数据添加到Core Data(使用tableview),删除现有数据

时间:2015-04-04 15:22:20

标签: ios objective-c xcode uitableview core-data

我试图将NSManagedObject添加到现有数据中,但在我做完之后,我的现有数据消失了,我无法弄清楚原因。看一个小时的代码无济于事:(

FirstTableViewController.m // DELEGATE指向AppDelegate

- (void)viewDidLoad {
    [super viewDidLoad];
    self.context=[DELEGATE managedObjectContext];
    self.everyWish=[[NSMutableArray alloc]initWithArray:[DELEGATE collectSharedWishes]]; //collects every shared wishes from core data
    self.emberek=[[NSMutableArray alloc]initWithArray:[DELEGATE collectUserNames]]; //collects every user
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:IDENTIFIER forIndexPath:indexPath];

    User *emberek=[self.emberek objectAtIndex:indexPath.row];
    NSMutableArray *currentUserWishes=[[NSMutableArray alloc]initWithArray:[DELEGATE collectCurrentUserSharedWishes:emberek]]; //collects the current user wishes only from core data 

    int completed=0;
    for(SharedWishes *wish in currentUserWishes)
        if([wish.wishIsPurchased isEqual:@1])
            completed++;

    cell.textLabel.text=emberek.userName;
    cell.detailTextLabel.text=[NSString stringWithFormat:@"Wishes: %lu, purchased: %d", (unsigned long)currentUserWishes.count, completed];

    return cell;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if([segue.identifier isEqualToString:@"pushToCurrentUser"]){

        User *user=[self.emberek objectAtIndex:[[self.tableView indexPathForSelectedRow]row]];

        SharedTableViewController *wishTVC=[segue destinationViewController];
        wishTVC.user=user;
        NSLog(@"%@", user);
    }
}

OtherTableViewController.h

@property NSManagedObjectContext *context;
@property User *user;

OtherTableViewController.m

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.context=[DELEGATE managedObjectContext];
    self.format=[[NSDateFormatter alloc]init];
    self.todayFormat=[[NSDateFormatter alloc]init];

    self.results=[[NSMutableArray alloc]init];
    self.wishes=[[NSMutableArray alloc]initWithArray:[DELEGATE collectCurrentUserSharedWishes:self.user]];
    self.navigationItem.title=[NSString stringWithFormat:@"%@'s list", self.user.userName];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshTableViewData) name:@"refreshTableViewData" object:nil];

    self.refreshControl=[[UIRefreshControl alloc] init];
    [self.refreshControl setTintColor:[UIColor redColor]];
    [self.tableView addSubview:self.refreshControl];
    [self.refreshControl addTarget:self action:@selector(pullDownToRefresh:) forControlEvents:UIControlEventValueChanged];
}

-(void)fetch:(CKRecord *)obj
{
    NSError *error;
    SharedWishes *wish=[NSEntityDescription insertNewObjectForEntityForName:@"SharedWishes" inManagedObjectContext:self.context];

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"SharedWishes" inManagedObjectContext:self.context];
    [fetchRequest setEntity:entity];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"wishID==%@", obj.recordID.recordName];
    [fetchRequest setPredicate:predicate];

    NSArray *fetchedObjects = [self.context executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil)
        NSLog(@"Nem sikerult az ab-t elerni!, %@", [error localizedDescription]);

    if([fetchedObjects isEqual:@[]])
    {
        User *currentUser=[[DELEGATE fetchUserWithID:self.user.userID] objectAtIndex:0]; //fetches the current user, which i already have, tried before using [self.user addSharedWishesObject:wish]
        wish.wishName=obj[@"name"];
        wish.wishPrice=obj[@"price"];
        wish.wishIcon=obj[@"icon"];
        wish.wishTime=obj[@"creationDate"];

        wish.wishLocation=obj[@"location"];
        wish.wishDescription=obj[@"description"];
        wish.wishType=obj[@"type"];
        wish.wishURL=obj[@"url"];
        wish.wishImage=obj[@"image"];
        wish.wishID=obj.recordID.recordName;
        wish.wishIsPurchased=obj[@"purchased"];
        wish.wishChangeTag=obj.recordChangeTag;
        NSError *error;

        [currentUser addSharedWishesObject:wish];

        if(![self.context save:&error])
            NSLog(@"Nem tudtam eltarolni az adatbazisban, oka: %@", [error localizedDescription]);
    }
    else
    {
        wish=[fetchedObjects objectAtIndex:0];

        if(![wish.wishChangeTag isEqualToString:obj.recordChangeTag]){

            wish.wishName=obj[@"name"];
            wish.wishPrice=obj[@"price"];
            wish.wishIcon=obj[@"icon"];
            wish.wishTime=obj[@"creationDate"];

            wish.wishLocation=obj[@"location"];
            wish.wishDescription=obj[@"description"];
            wish.wishType=obj[@"type"];
            wish.wishURL=obj[@"url"];
            wish.wishImage=obj[@"image"];
            wish.wishID=obj.recordID.recordName;
            wish.wishIsPurchased=obj[@"purchased"];
            wish.wishChangeTag=obj.recordChangeTag;

            //wish.user.userID=obj.creatorUserRecordID.recordName;

            NSError *error;
            if(![self.context save:&error])
                NSLog(@"Nem tudtam eltarolni az adatbazisban, oka: %@", [error localizedDescription]);
        }
    }
}

这是代码,它运行没有错误,一切都声明正确,虽然我没有提到(为了简化我的代码)。 运行后,我拥有所有用户,但只显示最后一个用户的愿望,从FirsTableViewController调用NSMutableArray *currentUserWishes=[[NSMutableArray alloc]initWithArray:[DELEGATE collectCurrentUserSharedWishes:emberek]];。最后一个具有正确数量的对象,之前的对象具有@" 0个对象"。

将它们保存在OtherTableViewController中?有什么想法吗? ps:如果需要,发布更多详细信息

1 个答案:

答案 0 :(得分:0)

BUG已修复: 在我保存对象之后,我调用了一个方法,在其中我将我的元素(在我的数据库中)与云元素进行比较,并从我的持久数据库中删除云中不再可用的元素。 “错误”谓词导致了主要问题,因为我查询了所有数据库对象,而不是特定用户的元素