Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer to NSInteger And Save To Core Data

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

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

With this code, I get the warning:

warning: Semantic Issue: Incompatible integer to pointer conversion sending 'int' to parameter of type 'id'

So, How do I set the value for an NSInteger.

Next Question, How do re-upload the array into core data? I fetch the array, make changes, and how do I apply those changes back to Core Data?

Thanks

like image 984
Ahan Malhotra Avatar asked Dec 01 '22 07:12

Ahan Malhotra


2 Answers

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

like image 22
Oscar Gomez Avatar answered Dec 04 '22 06:12

Oscar Gomez


Initialize an NSNumber (which is what CoreData is expecting) with your integer:

NSNumber *marbleNumber = [NSNumber numberWithInt:marbles];
[records setObject:marbleNumber forKey@"marbles"];

Or:

[records setMarbles:[NSNumber numberWithInt:marbles]];

To persist your changes, you save your context:

NSError *error;
[myManagedObjectContext save:&error];

//handle your error
like image 179
isaac Avatar answered Dec 04 '22 06:12

isaac