Search code examples
iphoneobjective-cioscore-datanscopying

Save CoreData result array even after it is deleted from the CoreData


I want to save the records in an array and delete them from the CoreData. I have tried using NSCopying but it seems that copyWithZone doesn't work on NSManagedObject. I am really stuck, any help will be appreciated.


Solution

  • Copy all the field values of your NSManagedObject to an Dictionary, and store these dictionaries in the array.

    I've put together a small routine that you can implement in a NSMutableObject category that could be used to obtain that.

    (please, be aware that I'm not on a Mac computer right now and there might be typos on the code, but other than that, it should work fine).

    -(NSDictionary*)retrieveAsDict {
      NSMutableDictionary *aux = [[NSMutableDictionary alloc] init];
      NSDictionary *attributes = [self attributesByName];
      NSArray *attributeNames = [attributes allKeys];
    
      for (NSString *key in attributeNames) {
        [aux setValue:[self valueForKey:key] forKey:key];
      }
    
      NSDictionary *ret = [NSDictionary dictionaryWithDictionary:aux];
    
      // Uncomment this if not using ARC
      //[aux release];
    
      return(ret);
    }
    

    If you need further clarification, be sure to comment and I'll answer shortly.