Leonard Wilson
Leonard Wilson

Reputation: 82

Take a number from JSON and use it to setValue to Int 32 in Core Data

I have an array, pulled from JSON received from a web service. When I use NSLOG to view the contents of the array, it displays like this:

{ ?    Category = "New Products";
    CategoryID = 104;
    SubCategories =     (
    );
}

I need to take the Category and CategoryID values and assign them to the managed object "newProductCategory". I have no problem assigning the Category value, which corresponds to a string type, and I have no problem assigning a hard-coded number to the int 32 type that's supposed to receive the Category ID. But I've been struggling when it comes to converting the CategoryID value into anything that will be accepted as the int 32 type.

What's the proper syntax for converting that value into something digestible for this line of code, in place of the zero?

[newProductCategory setValue : 0 forKey : @"productCategoryID"];

Here's one of my failed attempts that might be informative. When I try...

        // Pull category record "i" from JSON        
        NSArray * categoryProperties = [categories objectAtIndex:i];
        NSNumber * productCategoryID = [categoryProperties valueForKey:@"CategoryID"];

... then I attempt to assign it in the above format, using productCategoryID in place of the zero, it produces the following error:

'NSInvalidArgumentException', reason: 'Unacceptable type of value for attribute: property = "parentCategoryID"; desired type = NSNumber; given type = __NSCFString; value = 104.'

Upvotes: 1

Views: 739

Answers (2)

Boris Charpentier
Boris Charpentier

Reputation: 3543

Even if you specify int32 in CoreData, you will pass a NSNumber object, and it seems that you get a NSString from the json parsing (you can try a log of NSStringFromClass([productCategoryID class]) to be sure). You can try :

NSString * productCategoryID = [categoryProperties valueForKey:@"CategoryID"];
newProductCategory.productCategoryID = @([productCategoryID intValue]);
//or
newProductCategory.productCategoryID = [NSNumber numberWithInt:[productCategoryID intValue]];

Upvotes: 3

graver
graver

Reputation: 15213

You need to set NSNumber, there are 2 ways:

[newProductCategory setValue:@(0) forKey:@"productCategoryID"];

or

[newProductCategory setValue:[NSNumber numberWithInt:0] forKey:@"productCategoryID"];

Upvotes: 0

Related Questions