Kirtikumar A.
Kirtikumar A.

Reputation: 4204

Core NSManagedObjectID always return object 0 in iphone

I want to fetch primary key value in core data in Iphone, so I am using NSManagedObjectID to get objectID(Mostly same as PK value ) but I am having problem that It return 0 always

Here is my code block

-(NSManagedObject *)existingObjectWithID:(NSManagedObjectID *)objectID
{

Maintness_Item *MainItem1; // my object model 
NSManagedObjectID *yourManagedObjectID = [ MainItem1 objectID];
int yourManagedObject_PK = [[[[[yourManagedObjectID URIRepresentation] absoluteString]    lastPathComponent] substringFromIndex:1] intValue];
NSLog(@"This is my managed object ID ...................%d",yourManagedObject_PK);

return 0;
}

Note: Here I am returning 0 ,Is it may problem? If any then what should I write here?

Please guide me

Upvotes: 1

Views: 1386

Answers (2)

Tom Harrington
Tom Harrington

Reputation: 70936

NSManagedObjectID doesn't work like that, and neither does NSString.

If the managed object hasn't been saved yet, the object ID's absolute string will be something like:

x-coredata:///Entity/tE7D63E10-8BE4-41CE-A6DC-C131F6990F062

If it has been saved, it will be something like

x-coredata://F869550C-914E-4160-B8A7-9DD9A82F2CE2/Entity/p2

Neither version presents any good targets for -[NSString intValue]. You might extract the integer at the end, but this is not in any way useful, not even a little bit. You can't use that integer value for anything, anywhere.

Upvotes: 0

Mundi
Mundi

Reputation: 80265

I think you should not use the object id as the private key. It is not an integer and has its own representation. NSManagedObjectID is really there for persisting a reference to a particular entity in e.g. user defaults, or to create weak references ("joins") across persistent stores.

There is a URL representation you can use:

NSURL *uri = [[myObject objectID] URIRepresentation];

You can turn that into NSData if you want to keep it, but you could also just serialize the URI.

If you need classic private keys e.g. to communicate with another instance of your data on a server, you should create your own as attributes of your entities. Just don't abuse them to substitute managed object model relationships.

NB: please UpperCaseNames only for classes, for instances you should use lowerCaseName.

Upvotes: 3

Related Questions