Integer to NSInteger And Save To Core Data

后端 未结 3 978
遥遥无期
遥遥无期 2021-01-03 06:56

I have a integer named marbles, and am trying to save it into an array using the following code:

[records setValue:marbles forKey:@\"marbles\"];
3条回答
  •  不知归路
    2021-01-03 07:49

    NSArrays will only take objects, so the first step is to turn your NSInteger into a NSNumber using this method:

    + (NSNumber *)numberWithInt:(int)value
    

    so:

    NSNumber *myNumber = [NSNumber numberWithInt:marbles];
    

    and then you can do:

    [records setValue:myNumber forKey:@"marbles"];
    

    Basically once you fetch the data, you get a managedObjectContext, think of it as a drawing board, and any changes (including adding or deleting new objects), you make to this objects may be saved again to CoreData using something like this:

    NSError *error;
            if (![context save:&error]) {
                // Update to handle the error appropriately.
                NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
                exit(-1);  // Fail
            }
    

    Where context is the context you would get with your NSFetchedResultsController. Which you can get like this:

    NSManagedObjectContext *context = [fetchedResultsController managedObjectContext];
    

    I would recommend taking a look at the Core Data programming guide

提交回复
热议问题