Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSManagedObject: isUpdated and isInserted

I keep track of my 'objects' using the isUpdated instance method of NSManagedObject Class.

When I'm modifying an exisiting object, it works.

If I create a new object using for example:

[NSEntityDescription insertNewObjectForEntityForName:@"Entity" inManagedObjectContext:managedObjectContext]

I can't use the isUpdated, I have to use the isInserted.

This works, but what I want to check, if the object has been modified with new data.

isInserted will return FALSE no matter if the object has been changed or not, it only take care if has been inserted or not ...

what can I use ? I can track the initial state of the object properties but I would prefer the isUpdated approach.

thanks!!!

r.

like image 736
mongeta Avatar asked Feb 16 '10 19:02

mongeta


People also ask

What is NSManagedObject in Core Data?

In some respects, an NSManagedObject acts like a dictionary—it's a generic container object that provides efficient storage for the properties defined by its associated NSEntityDescription instance.

What is an Nsmanagedobjectid?

A compact, universal identifier for a managed object.

What is Nsmanagedobjectcontext?

An object space to manipulate and track changes to managed objects.

Can we have multiple managed object context in Core Data?

Most apps need just a single managed object context. The default configuration in most Core Data apps is a single managed object context associated with the main queue. Multiple managed object contexts make your apps harder to debug; it's not something you'd use in every app, in every situation.


2 Answers

I'm not sure i completely understand your question, however, if you want to check whether your working with an unsaved new NSManagedObject, you can do that by writing a small category for NSManagedObject:

@interface NSManagedObject(Utility)

/**
 Returns YES if this managed object is new and has not yet been saved in the persistent store.
 */
- (BOOL)isNew;

@end

@implementation NSManagedObject(Utility)

- (BOOL)isNew {
    NSDictionary *vals = [self committedValuesForKeys:nil];
    return [vals count] == 0;
}

@end

If you've created a new managed object using:

[NSEntityDescription insertNewObjectForEntityForName:@"Entity" inManagedObjectContext:managedObjectContext]

You can use the -isNew method to check whether it has been saved or not.

like image 84
Mustafa Avatar answered Sep 29 '22 06:09

Mustafa


isInserted indicates if the object is "new" (newly inserted to NSManagedObjectContext). I think what You need is method hasChanges (it's on NSManagedObject and also on NSManagedObjectContext)...

BOOL someChangeHappendToObject = [myObject hasChanges];

checkout NSManagedObject hasChanges documentation

like image 35
JakubKnejzlik Avatar answered Sep 29 '22 07:09

JakubKnejzlik