1

I have an NSArray called namesArray.

I need to store all the names existing in namesArray using coredata.

How do i achieve this ?

Does we need to create any database like 'names.sqlite' using sqlite manager?

iNoob
  • 3,364
  • 2
  • 26
  • 33
Ranga
  • 821
  • 4
  • 11
  • 20

2 Answers2

1

No you don't need to create a names.sqlite using manager. You should go through some of the tutorial found on the net for example: Here or Here.

You basically need to save in the datamodel in valueForKey format.

   //Coredata saving
 self.theAppDel=[[UIApplication sharedApplication] delegate];
 NSManagedObjectContext*context=[self.theAppDel managedObjectContext];
 NSManagedObject*object=[NSEntityDescription insertNewObjectForEntityForName:@"Contacts" inManagedObjectContext:context];
 NSError*error=nil;

 [object setValue:[namesArray objectAtIndex:0] forKey:@"name"]; //for saving first name

1. Creating an instance of your appdelegate .

2. Access your Managed Object Context and Managed Object

3. Assuming you created a entity description with name contacts. With the count of number of items in your array, add each object for a column named name (which i'm assuming you would have created).

This is short example, but you should go through the tutorials and read apple's documentation.

EDIT: As Ondra mentioned my earlier solution would have added only the last element. Use the following for adding: Adding NSMutableArray in CoreData Thanks Ondra Peterka

Community
  • 1
  • 1
iNoob
  • 3,364
  • 2
  • 26
  • 33
1

I think that iNoobs answer would not work - the loop would overwrite the value several times (only last name would be saved). In every case reading the tutorials is good idea. Maybe the answer you are looking for is here: Saving an NSMutableArray to Core Data

Also ... I know you explicitly said "save to core data", but just in case - you can use also different storage like NSUserDefaults:

[[NSUserDefaults standardUserDefaults] setObject:namesArray forKey:@"namesArray"];

and retrieve it later using:

myArray= [[NSMutableArray alloc] initWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"namesArray"]];

Of course NSUserDefaults are ment to be used only for small amount of data.

Good luck ;)

Community
  • 1
  • 1
Ondrej Peterka
  • 3,349
  • 4
  • 35
  • 49