F-Script and Core Data

F-Script has very powerful support for array and set operations. This makes it particularly interesting when analyzing core data as it allows very easy querying of the data sets.

The first part is setting up the core data entities array in F-Script - this is pretty lengthy as you have to load both the object model and the managed object context tied to the persistent store holding the actual data.

If you want to paste the data below in the F-Script interpreter window, press F7. F-Script will say "When pasting command, newline is now interpreted as subcommands separator"


mompath := NSString stringWithString:'/Users/diciu/FoodBrowser/build/Release/FoodBrowser.app/Contents/Resources/FoodHistory.mom'
momurl := NSURL URLWithString:mompath
mom := NSManagedObjectModel alloc initWithContentsOfURL:momurl

pstore := NSPersistentStoreCoordinator alloc initWithManagedObjectModel:mom

sqfile := NSString stringWithString:'/Users/diciu/Library/Application Support/FoodBrowser/FoodHistory.sql'
sqfileurl := NSURL fileURLWithPath:sqfile
pstore addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:sqfileurl options:nil error:nil

mocontext:= NSManagedObjectContext alloc init
mocontext setPersistentStoreCoordinator:pstore

edes := NSEntityDescription entityForName:'FoodItem' inManagedObjectContext:mocontext
fetchreq := NSFetchRequest alloc init
fetchreq setEntity:edes

dataitems := mocontext executeFetchRequest:fetchreq error:nil


Once you've fetched your data, you can use the power of F-Script to analyze it:


> dataitems
_PFArray { (entity: FoodItem; id: 0x4da020 ; data: {
energy = 380;
name = "Snacks, pretzels, hard, plain, salted";
quantity = 100;
time = 2008-06-27 09:30:00 +0300;
value = 380;
}),
(entity: FoodItem; id: 0xda192c0 ; data: {
energy = 0;
name = "Water, bottled, generic";
quantity = 100;
time = 2008-06-27 10:02:00 +0300;
value = 0;
}),



Running sum through reduction:


> (dataitems energy) \#+
19777.38003540039


Average:

> (dataitems energy) \#+ / (dataitems count)
229.9695352953534


Maximum:

> (dataitems energy) \#max:
1080


Minimum

> (dataitems energy) \#min:
0


Is minimum value sane? (retrieve the index)

> (dataitems energy) ! ((dataitems energy) \#min:)
1



Print the object at index one:

> dataitems at:1
(entity: FoodItem; id: 0xda192c0 ; data: {
energy = 0;
name = "Water, bottled, generic";
quantity = 100;
time = 2008-06-27 10:02:00 +0300;
value = 0;
})




To run the graphical browser on the set of managed items, use:


> sys browse:dataitems






Reference: ExploringCocoaWithFScript