-1

I am trying to convert a NSNumber to long but I get this error:

[__NSSingleObjectArrayI intValue]: unrecognized selector sent to instance

Here is my code:

NSNumber *dbversion = [settings valueForKey:@"Version"];
long dbver = [dbversion longValue];

What am I doing wrong here?

*settings is a NSArray and "Version" is the key for a long value.

Steve
  • 1
  • 4

2 Answers2

2

You are caught in the Key-Value Coding trap.

In some cases the result of valueForKey is an array which the error message clearly states.

Don't Never use valueForKey(unless you know what KVC does and you need KVC), use key subscription.

And as settings is an array you might get the first item

NSNumber *dbversion = settings[0][@"Version"];

and int is not long

long dbver = [dbversion longValue];

However on a 64-bit machine I recommend to use NSInteger

NSInteger dbver = dbversion.integerValue;
vadian
  • 274,689
  • 30
  • 353
  • 361
  • I'd may go even further: The author seems to be debuting (the error is explicit and well known for experienced dev). For debutants, I would suggest to NEVER use `valueForKey:`, results can be misleading for them on future use. – Larme Apr 05 '18 at 08:00
  • There is an error when I use the first line of code you wrote: Expected method to read dictionary element not found on object of type 'NSArray – Steve Apr 05 '18 at 08:01
  • settings is an NSArray object – Steve Apr 05 '18 at 08:01
  • Then your syntax is wrong anyway. An array is subscripted by index e.g. `settings[0]` – vadian Apr 05 '18 at 08:05
  • Could you print `settings`? @vadian made guesses on its structure, and his responses is legit, but might not be quite fully adequate with your current situation that you might need to adapt or give use `settings` so he can adapts its answers. – Larme Apr 05 '18 at 08:07
  • @Steve An Array doesn't have keys. It may have some objects that are dictionaries which have keys like: `settings = @[@{@"Version":@(versionNumber)}]`? – Larme Apr 05 '18 at 08:11
  • You are right, that was my mistake. I have an object inside it and inside that object is the "Version" value. – Steve Apr 05 '18 at 08:11
0

//I think you are storing string from dictionary "settings" to NSNumber so it's showing error like you mention in question. Please Try with solution. May this help you.

NSNumber *dbversion = [NSNumber numberWithLong:[[settings valueForKey:@"Version"] longLongValue]];
int dbver = [dbversion longValue];
Yagnesh Dobariya
  • 2,241
  • 19
  • 29