• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Core Data: Insert, Fetch, Re-Fetch. Same Object?
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Core Data: Insert, Fetch, Re-Fetch. Same Object?


  • Subject: Core Data: Insert, Fetch, Re-Fetch. Same Object?
  • From: Jerry Krinock <email@hidden>
  • Date: Wed, 10 Feb 2010 16:44:10 -0800

I've always wondered if I insert a managed object, then later fetch it repeatedly from the same managed object context, do I get the same object every time?  (Assume that there is only one object which matches the given predicate.)  This may be important if I want to, say, set an instance variable value.

So I just wrote a little experiment, using an in-memory store, and found that the answer is yes, even if I run a run loop and fetch on a timer.

Is this expected, or is this an implementation detail which Apple may change at any time?

Thanks,

Jerry


CONSOLE OUTPUT:

       Inserted: Foo 0x1e0e960 name=Murphy ivar=Squawk
  First Fetched: Foo 0x1e0e960 name=Murphy ivar=Squawk
 Second Fetched: Foo 0x1e0e960 name=Murphy ivar=Squawk
  Delay Fetched: Foo 0x1e0e960 name=Murphy ivar=Squawk
  Delay Fetched: Foo 0x1e0e960 name=Murphy ivar=Squawk
  Delay Fetched: Foo 0x1e0e960 name=Murphy ivar=Squawk
  ...


CODE (A Cocoa Tool Project):

#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>

@interface Foo : NSManagedObject {
    NSString* m_ivar ;
}

@property (copy) NSString* ivar ;

@end

@implementation Foo

@synthesize ivar = m_ivar ;

- (void)dealloc {
    [m_ivar release] ;

    [super dealloc] ;
}

- (NSString*)description {
    return [NSString stringWithFormat:
            @"Foo %p name=%@ ivar=%@",
            self,
            [self valueForKey:@"name"],
            [self ivar]] ;
}

@end


// Note: This function returns a retained, not autoreleased, instance.
NSManagedObjectModel *getStaticManagedObjectModel() {
    static NSManagedObjectModel *mom = nil;

    if (mom != nil) {
        return mom;
    }

    mom = [[NSManagedObjectModel alloc] init];

    NSEntityDescription *fooEntity = [[NSEntityDescription alloc] init];
    [fooEntity setName:@"Foo"];
    [fooEntity setManagedObjectClassName:@"Foo"];
    [mom setEntities:[NSArray arrayWithObject:fooEntity]];

    NSMutableArray* properties = [[NSMutableArray alloc] init] ;
    NSAttributeDescription *attributeDescription;

    // Add an attribute.  (Copy this section to add more attributes.)
    attributeDescription = [[NSAttributeDescription alloc] init];
    [attributeDescription setName:@"name"];
    [attributeDescription setAttributeType:NSStringAttributeType];
    [attributeDescription setOptional:YES];
    [properties addObject:attributeDescription] ;
    [attributeDescription release] ;

    [fooEntity setProperties:properties];
    [properties release] ;

    [fooEntity release] ;

    return mom;
}

// Note: This function returns a retained, not autoreleased, instance.
NSManagedObjectContext *getStaticManagedObjectContext() {

    static NSManagedObjectContext *moc = nil;

    if (moc != nil) {
        return moc;
    }

    moc = [[NSManagedObjectContext alloc] init];

    NSPersistentStoreCoordinator *coordinator =
    [[NSPersistentStoreCoordinator alloc]
     initWithManagedObjectModel:getStaticManagedObjectModel()];
    [moc setPersistentStoreCoordinator: coordinator];
    [coordinator release] ;

    NSError *error;
    NSPersistentStore *newStore ;
    newStore = [coordinator addPersistentStoreWithType:NSInMemoryStoreType
                                         configuration:nil
                                                   URL:nil
                                               options:nil
                                                 error:&error];

    if (newStore == nil) {
        NSLog(@"Store Configuration Failure\n%@",
              ([error localizedDescription] != nil) ?
              [error localizedDescription] : @"Unknown Error");
    }
    return moc;
}


@interface DelayedFetcher : NSObject {
}

@end

@implementation DelayedFetcher

+ (void)fetchFoo:(NSTimer*)timer {
    NSFetchRequest* fetchRequest = [[NSFetchRequest alloc] init];
    NSManagedObjectContext *moc = getStaticManagedObjectContext() ;
    [fetchRequest setEntity:[NSEntityDescription entityForName:@"Foo"
                                        inManagedObjectContext:moc]];
    NSArray* fetches = [moc executeFetchRequest:fetchRequest
                                          error:NULL] ;
    [fetchRequest release] ;
    Foo* delayFetchedFoo = [fetches objectAtIndex:0] ;
    NSLog(@" Delay Fetched: %@", delayFetchedFoo) ;
}

@end


int main (int argc, const char * argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    // Create Core Data stack
    NSManagedObjectModel *mom = getStaticManagedObjectModel();
    NSManagedObjectContext *moc = getStaticManagedObjectContext();

    // Insert a Foo and name it "Murphy"
    Foo* insertedFoo = [NSEntityDescription insertNewObjectForEntityForName:@"Foo"
                                                     inManagedObjectContext:moc] ;
    [insertedFoo setValue:@"Murphy"
                   forKey:@"name"] ;
    [insertedFoo setIvar:@"Squawk"] ;

    [moc processPendingChanges] ;
    [moc save:NULL] ;

    NSFetchRequest* fetchRequest ;
    NSArray* fetches ;

    // Fetch the Foo
    fetchRequest = [[NSFetchRequest alloc] init];
    [fetchRequest setEntity:[NSEntityDescription entityForName:@"Foo"
                                        inManagedObjectContext:moc]];
    fetches = [moc executeFetchRequest:fetchRequest
                                 error:NULL] ;
    [fetchRequest release] ;
    Foo* firstFetchedFoo = [fetches objectAtIndex:0] ;

    // Fetch the Foo again
    fetchRequest = [[NSFetchRequest alloc] init];
    [fetchRequest setEntity:[NSEntityDescription entityForName:@"Foo"
                                        inManagedObjectContext:moc]];
    fetches = [moc executeFetchRequest:fetchRequest
                                 error:NULL] ;
    [fetchRequest release] ;
    Foo* secondFetchedFoo = [fetches objectAtIndex:0] ;

    // See what we got
    NSLog(@"      Inserted: %@", insertedFoo) ;
    NSLog(@" First Fetched: %@", firstFetchedFoo) ;
    NSLog(@"Second Fetched: %@", secondFetchedFoo) ;

    // Fetch again and again
    NSRunLoop* runLoop = [NSRunLoop currentRunLoop] ;
    [NSTimer scheduledTimerWithTimeInterval:1.0
                                     target:[DelayedFetcher class]
                                   selector:@selector(fetchFoo:)
                                   userInfo:nil
                                    repeats:YES] ;
    [runLoop run] ;

    [moc release] ;
    [mom release] ;
    [pool release] ;

    return 0;
}_______________________________________________

Cocoa-dev mailing list (email@hidden)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:

This email sent to email@hidden

  • Follow-Ups:
    • Re: Core Data: Insert, Fetch, Re-Fetch. Same Object?
      • From: Jens Alfke <email@hidden>
  • Prev by Date: Re: Using NSKeyedArchiver to save and restore state on iPhone apps
  • Next by Date: Re: NSXML and >
  • Previous by thread: NSTableView not supplying expected object type
  • Next by thread: Re: Core Data: Insert, Fetch, Re-Fetch. Same Object?
  • Index(es):
    • Date
    • Thread