Markus
Markus

Reputation: 1177

How to Read and Use Integer value from Core Data

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?

Upvotes: 0

Views: 627

Answers (1)

Wain
Wain

Reputation: 119041

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]

Upvotes: 2

Related Questions