Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an NSManagedObject with NSDictionary contents

I want to create an NSManagedObject with the contents of a NsDictionary. and Visa Versa.

I have a NSDictionary with object and keys that is being brought in from a MYSQL database and stored to the documents directory. I can't find good info for editing a dictionary so I thought I would try NSManaged Object instead.

If the Object attributes get changed I want to be able to reverse the procedure and send the object back.

Any help of finding an example of this would be great.

Thanks,

Michael

like image 386
Michael Robinson Avatar asked Jul 14 '10 01:07

Michael Robinson


People also ask

How do I create an NSDictionary in Objective C?

Creating NSDictionary Objects Using Dictionary Literals In addition to the provided initializers, such as init(objects:forKeys:) , you can create an NSDictionary object using a dictionary literal. In Objective-C, the compiler generates code that makes an underlying call to the init(objects:forKeys:count:) method.

Does NSDictionary retain objects?

An NSDictionary will retain it's objects, and copy it's keys. Here are some effects this has had on code I've worked on. Sometimes you get the same object you put in, sometimes not. Immutable objects are optimized to return themselves as a copy .

What is the difference between NSDictionary and NSMutableDictionary?

Main Difference is:NSMutableDictionary is derived from NSDictionary, it has all the methods of NSDictionary. NSMutableDictionary is mutable( can be modified) but NSDictionary is immutable (can not be modified).

What is managed object context?

A managed object context represents a single object space, or scratch pad, in a Core Data application. A managed object context is an instance of NSManagedObjectContext . Its primary responsibility is to manage a collection of managed objects.


1 Answers

Here is how I am doing this for creating the NSManagedObject, works like a charm:

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:kParentChildSKUSUrl,@"8"]];
NSArray *array = [[NSArray alloc] initWithContentsOfURL:url];

int j = 0;
int saveThreshold = 500;

for (NSDictionary* dict in array) {
  j+=1;
  ParentChildSKU *entity = (ParentChildSKU*) [NSEntityDescription   insertNewObjectForEntityForName:@"ParentChildSKU" inManagedObjectContext:managedObjectContext];
  [entity setValuesForKeysWithDictionary:dict];

  if (j%saveThreshold==0) {
    NSLog(@"Saving after 500 items");
    NSError *error;
    if (![managedObjectContext save:&error]) {
    // Handle the error.
     }
  }             
}

See this question also, this is where I got started: Plist Array to NSDictionary

like image 176
Slee Avatar answered Sep 30 '22 18:09

Slee