0
votes

I will reframe the question:

I use Core Data and I define an Entity with an Attribute: attribute1 as Integer16.

I read the attribute:

NSArray *objects = [objectContext executeFetchRequest:request error:&error];

int integer1 = [[objects valueForKey:@"attribute1"] integerValue]

In this last sentence App crashes.

The aim is to realise the arithmetic:

int integer2 = 0;

integer2 = integer2 + integer1;

Maybe I must work with NSNumber, NSInteger, NSUInteger?

Really, I do not understand how something so simple is so complicated with Objective C.

No comment...

Original question:

First, I work with XCode 5 (iOS 7)

I have defined an Entity with an Attribute countStep as Integer 16. In that attribute I have saved a value (i.e. 10)

Later, I want to read that value:

int integerVal1 = [[objects valueForKey:@"countStep"] integerValue];

With the intention to realise arithmetic operations:

int integerVal2;

integerVal2 = integerVal2 + integerVal1

But in source line:

int integerVal1 = [[objects valueForKey:@"countStep"] integerValue];

App crashes with error message:

* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI integerValue]: unrecognized selector sent to instance

I have tried several alternatives.

@property (nonatomic, assign) int integerVal2;

Or:

NSString *string = [[objects valueForKey:@"countStep"]description];

int integerVal1 = [NSNumber numberWithInteger:[string intValue]];

integerVal2 = integerVal2 + integerVal1

The problem is the same: convert a dictionary object to primitive element int (integer) to compute arithmetic operations: integerVal2 = integerVal2 + integerVal1

Any idea?

1
The error says countStep is an array. How is it an array? How are you setting the value? Have you added any custom code to your entity?Wain
countStep is the name of the Attribute in Core Data. The question is: how can I realise sums with an integer (i.e. 10, 5 or whatever) saved in Core Data?Markus
Being an Integer 16 as you describe is correct. But the runtime says you haven't done that - hence the exception.Wain
I will reframe the question. Sorry for the misunderstanding.Markus
How are you setting the number and saving it to core data?Wain

1 Answers

2
votes

Ok, reading your code carefully... This:

NSArray *objects = [objectContext executeFetchRequest:request error:&error];

int integer1 = [[objects valueForKey:@"attribute1"] integerValue]

will never work, because calling valueForKey: on an array returns an array. So when you call integerValue you get an exception.

What you should do is:

NSArray *objects = [objectContext executeFetchRequest:request error:&error];
id myEntity = objects[0]; // put protection around this...
int integer1 = [[myEntity valueForKey:@"attribute1"] integerValue]