user1904273
user1904273

Reputation: 4764

Set value for key in case of NSInteger

I am trying to set a value in core data using setValue:forKey: but it is throwing an error:

(Use of undeclared identifier: 'newID'}

when trying to save an NSInteger. Can anyone suggest the correct syntax?

 NSInteger newID = lastID+1;
 [record setValue:newID forKey:@"localid"];//error 

Got similar error when I tried setObject instead of setValue

Upvotes: 1

Views: 2552

Answers (2)

Tamás Zahola
Tamás Zahola

Reputation: 9319

NSInteger is a primitive type, not an object. You should box it into an NSNumber like this:

NSInteger newID = lastID+1;
 [record setValue:@(newID) forKey:@"localid"];

And you can convert back like this:

NSInteger recordId = [((NSNumber*)[record valueForKey:@"localid"]) integerValue]

Upvotes: 4

gnasher729
gnasher729

Reputation: 52538

You can only set NSObject. Simplest way is

record [@"localid"] = @(newID);

And you should avoid setValue:forKey: and valueForKey: and either use setObject: and objectForKey: or the modern syntax - unless you have a good reason why you'd want the "value" methods.

Upvotes: 1

Related Questions