views:

16

answers:

1

Hi All, I am new to ObjC and newer still to CoreData. I have tried to find an answer to this around but never got quite what happens to me. I initialize a Managed object in my controller's loadView like this:

NSError    *error;
  NSFetchRequest  *request = [[NSFetchRequest alloc] init];
  NSEntityDescription *entity  = [NSEntityDescription entityForName: @"Info"
               inManagedObjectContext: [self managedObjectContext]];
  [request setEntity: entity];

  NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
  if (mutableFetchResults == nil)
  { /* Handle the error. */ }
  else
  {
   if( [mutableFetchResults count] == 1 )
   {
    info = (Info*) [mutableFetchResults objectAtIndex: 0 ];
   }
   else if( [mutableFetchResults count] == 0 )
   {
    info = (Info*) [NSEntityDescription insertNewObjectForEntityForName:@"Info"
                inManagedObjectContext:[self managedObjectContext]];
    [info setEventsArray: [[[NSArray alloc] init] autorelease]];
    [info setName:@"Holas"];
    if ( ![managedObjectContext save:&error] )
    {/* Handle the error. */}
    else
    {
     NSString *name = [info name];
     NSArray  *array = (NSArray*)[info eventsArray];
     int   a  = [array count];
     DebugStr(@"", a, name);
    }
   }
   else
   {/* Handle the error. */}
  };
  [mutableFetchResults release];
  [request release];

When checking just before DebugStr here, I can normally access properties name and eventsArray. Now, when handling and event with the following code (in a member of the same controller):

 Info   *myInfoObj  = [self info];
 NSString  *name   = [myInfoObj name];
 NSArray   *anEventsArray = (NSArray*)[myInfoObj eventsArray];
 DebugStr(@"", name, [anEventsArray count]);

...accessing 'name' throws an exception due to the accessor's being unrecognized. I am puzzled how Info's (Info is, by the way, derived from NSManagedObject) accessors are recognized in one context and not in the other. Are the dynamically (I think at run-time) generated accessors cached? I generated Info automatically with XCode, what am I missing? Thanks in advance for any clues.

+1  A: 

Hello,

It seems the problem is that the "info" object you get back from the fetch is not retained. When the mutableFetchResults array is released, the object is released and dealloc'ed. Accessing a dealloc'ed can result, amongst other symptoms, in a unrecognized method exception.

Hope it helps... Cam

tuscland
Hi Cam, this this the trick. In retrospect, it seems logical, since insertNewObjectForEntityForName does not have any of the signs that says I own its returned object. It's appealing (and misleading) though, how the exception thrown exception is not a null object dereference instead (is this the sting of dynamically typed languages all over again?).
NuBie