title: Storing an array of CGLayer to file
body: <p>I'm working on an OSX application where I need to store 446 CGLayers that get placed in a PDF context and am wondering if there's a way to write and read them from a file, rather than generating them when the application loads</p>
  
  <p>I've read that <a href="http://iosptl.com/posts/cglayer-no-longer-recommended/" rel="nofollow noreferrer">CGLayer is no longer recommended</a>, but I feel they really fit what I need.  Also, if I use bitmapGraphicsContexts, they can pixelate when zooming in.</p>
  
  <p>I am able to store them in NSArrays, both by <a href="https://stackoverflow.com/questions/1827943/how-to-save-and-read-a-cglayerref-in-a-nsmutablearray">storing them in NSValue</a> and <a href="https://stackoverflow.com/questions/7220398/cglayerref-in-nsvalue-when-to-call-retain-or-release?lq=1">puting them into the array by bridging</a>.  I've also tried storing them in C arrays, but that didn't work out.</p>
  
  <p>My problem comes when trying to store these arrays in a file.  writeToFile: doesn't work with CGLayers, but NSKeyedArchiver/NSKeyedUnarchiver hasn't worked either, both when the layers are in NSValues or bridged.</p>
  
  <p>Here's my method that attempts to write and read an array containing a single layer from a file.</p>
  
  <pre><code>+(CGLayerRef) colorAnnotations:(CGContextRef)context{    
  float symbolSize = 8;
  CGRect glyphBox = CGRectMake(0,0, 8, 8);    
  CGLayerRef   annotationLayer = CGLayerCreateWithContext (context,glyphBox.size, NULL);
  CGContextRef annotaionLayerContext = CGLayerGetContext(annotationLayer);
  
  CGMutablePathRef annot = CGPathCreateMutable();
  
  //Drawing annotation
  /*...*/
  
  NSMutableArray *test = [[NSMutableArray alloc]init];    
  [test addObject:[[NSValue alloc] initWithBytes:&amp;annotationLayer objCType:@encode(CGLayerRef)]];
  
  //Getting file path in Documents directory
  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  NSString *documentsDirectory = [paths objectAtIndex:0];
  NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"/annots.data"];
  
  [NSKeyedArchiver archiveRootObject:test toFile:dataPath];
  
  NSMutableArray *testLoads = [NSKeyedUnarchiver unarchiveObjectWithFile:dataPath];
  
  CGLayerRef layerToReturn;
  
  [[testLoads objectAtIndex:0]getValue:&amp;layerToReturn];
  
  return layerToReturn;
  }
  </code></pre>
  
  <p>I get <code>[NSKeyedArchiver encodeValueOfObjCType:at:]: unknown type encoding ('^')') was raised</code>from this, pretty sure because of the CGLayerRef type.</p>
  
  <p>The lines needed to draw the different annotations I need are pretty long, so I've been trying to figure out a way to have them made and stored in a file without having to make them on startup each time.  So far I'm not seeing a way to do this, but was hoping someone here may know of one and would appreciate any help.</p>