Core data how update a record?

倖福魔咒の 提交于 2020-01-15 08:29:27

问题


I have some object that is image that is in relation with object user mani-to-one like that Image <<---> User. Now that i want to do, when the user is login i display a button to each images for add to favourites, when i click this button is run this code:

User * user = [[UserController sharedInstance] currentUser];
Image * image = (Image*)[user.managedObjectContext objectWithID:[self.yacht objectID]];
yacht.whoLiked = user

the problem is not i the same controller but in the Main Controller before, because what i do is load al the image's thumb in a collection view (and in this controller load all the data from the DB) then when i press the thumb i go in another controller that show me the big image and the button for add favourites, when i press it and then come back to the old controller in the viewDidAppear of the old controller i reload every time the data from the db but i can't see any change, if i change section (controller) and i come back to see i see the data update

this is how I call the Db from Main Controller:

- (void)fetchImages
{
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Image"];
    request.predicate = [NSPredicate predicateWithFormat:@"ANY whichCategories.name =[cd] %@", self.category.name];
    NSSortDescriptor *sortName = [[NSSortDescriptor alloc] initWithKey:@"headline" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)];

    request.sortDescriptors = [NSArray arrayWithObject:sortName];
    NSError * error = nil;

    self.images = [self.database.managedObjectContext executeFetchRequest:request error:&error];
    [self.collectionView reloadData];


}

- (void)useDocument
{
    if (![[NSFileManager defaultManager] fileExistsAtPath:[self.database.fileURL path]]) {
        // CREATE
        [self.database saveToURL:self.database.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
             [self fetchImages];

        }];
    } else if (self.database.documentState == UIDocumentStateClosed) {
        // OPEN
        [self.database openWithCompletionHandler:^(BOOL success) {
                 [self fetchImages];
        }];
    } else if (self.database.documentState == UIDocumentStateNormal) {
        // USE
           [self fetchImages];


    }
}

- (void)setDatabase:(UIManagedDocument *)database
{
    if (_database != database) {
        _database = database;
        [self useDocument];
    }
}

-(void)viewDidAppear:(BOOL)animated{

    [super viewDidAppear:animated];
    [self useDocument];
    //[self.collectionView reloadData];
    [UIView beginAnimations:@"" context:nil];
    [UIView setAnimationDuration:0.5];
    self.collectionView.alpha = 1;
    [UIView commitAnimations];
}

Why if i come back and return the code work else is like that I didn't call the server for refresh the array?


回答1:


Triy with this code:

NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Favorits" inManagedObjectContext:moc]];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"title == %@", @"Some Title"];
[request setPredicate:predicate]; 

NSError *error = nil;
NSArray *results = [moc executeFetchRequest:request error:&error];

YourObject *object = [results objectAtIndex:0]; 
object.title = @"Bla bla bla";

//save changes
[moc save:&error];

if (error) {
   //Do something
}

this 2 link is helpful:

http://developer.apple.com/library/iOS/#documentation/Cocoa/Conceptual/CoreData/cdProgrammingGuide.html

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/CoreDataFramework/Classes/NSFetchRequest_Class/NSFetchRequest.html




回答2:


If I didn't misunderstand you, the problem is that when you refresh the array, your data is not updated.

If you reload from the DB and you haven't saved your changes, then you will get the values are in the DB. You should do:

NSError *saveError = nil;
[user.managedObjectContext save:&saveError];

if (error) {
  //Do whatever
}

You should use this code before call again the function to reload the array from the DB. The place it's up to you, but if you only call to refresh the array from DB when you are loading the viewcontroller, you can save the data when you are leaving the viewController.



来源:https://stackoverflow.com/questions/19520559/core-data-how-update-a-record

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!