title: Is there a reason I can't initialize a CALayer outside a UIView class?
body: <p>I have been trying to us CALayers as "sprites" in an iPhone application I'm working on. From what I have been reading, that seems like the correct thing to do here.</p>
  
  <p>When I setup the layer inside a UIView class I am able to get the layer to show up on the screen:
      NSLog(@"GameView initWithCoder");</p>
  
  <pre><code>NSString* imagePath = [[NSBundle mainBundle] pathForResource:@"earth" ofType:@"png"];
  earthImage = [[UIImage alloc] initWithContentsOfFile:imagePath];
  
  earthLayer = [CALayer layer];
  [earthLayer setContents:(id)[earthImage CGImage]];
  [earthLayer setBounds:CGRectMake(0, 0, 32, 32)];
  [earthLayer setPosition:CGPointMake(50, 50)];
  [earthLayer setName:@"earth"];
  
  [[self layer] addSublayer:earthLayer];
  </code></pre>
  
  <p>However, when I attempt to initialize the CALayer outside the UIView, my application crashes:</p>
  
  <pre><code>- (void)loadImage:(NSString*)fileName
  {
    NSLog(@"GamePiece loadImage");
    NSArray* fileNameParts = [fileName componentsSeparatedByString:@"."];
    imageName = [[fileNameParts objectAtIndex:0] retain];
    NSString* ext = [fileNameParts objectAtIndex:1];
  
    NSString* imagePath = [[NSBundle mainBundle] pathForResource:imageName ofType:ext];
    image = [[UIImage alloc] initWithContentsOfFile:imagePath];
  
    layer = [CALayer layer];
    [layer setContents:(id)[image CGImage]];
  
    [layer setBounds:CGRectMake(0.0f, 0.0f, 32.0f, 32.0f)];
    [layer setPosition:CGPointMake(50.0f, 50.0f)];
    [layer setName:imageName];
  
    [fileNameParts release], fileNameParts = nil;
    [ext release], ext = nil;
  }
  </code></pre>
  
  <hr>
  
  <pre><code>NSLog(@"GameView initWithCoder");
  earth = [[GamePiece alloc] init];
  [earth loadImage:@"earth.png"];
  
  [[self layer] addSublayer:[earth layer]];
  </code></pre>
  
  <p>Clearly I'm doing something wrong here, but I just don't know what that would be. I have read the Core Animation Programming Guide and also the iPhone Application Programming Guide, but they really don't seem to talk about how to initialize a CALayer other than in passing.</p>
  
  <p>I just need a gentle nudge in the correct direction. I have been getting a pretty good understanding about everything else I have learned when it comes to programming the iPhone. I'm just having some issues with Graphics, Layers and Animation.</p>
  
  <p>Thanks in advance!</p>