Archive for the 'Core Data' Category

Core Data / Array Controller: Edit on Insert

Thursday, May 18th, 2006

I’m writing a silly little Cocoa app to track my weight over time, trend line and all. Because, well, no task can be done without writing some code… right? right?!?!?!??

The app draws a graph of the weights in a window and allows the user to add new weights in a drawer with a simple table containing two columns; date & weight. Given the simplicity of the data being entered, I had no desire to have a detail view at the bottom containing date/weight fields.

Hooking a “+” button directly to the NSArrayController worked fine, but then the user had to click on the blank row in the table view to start entering data. Bad UE.

Fixing it is easy as long as you remember that you cannot use the target/action methods for adding items to the array controller because they attempt to do a bit of auto-editing setup themselves.

Simply create a action method like the following and make the “+” button fire said action method:

- (IBAction) insertNewWeight: sender;
{
	NSManagedObject *insertedObject = [weightEntryArrayController newObject];
	unsigned newRow = [weightinator rawWeightCount];
	[weightEntryArrayController insertObject: insertedObject atArrangedObjectIndex: newRow];
	[weightEntryTableView editColumn: 0 row: newRow withEvent: nil select: YES];
	[insertedObject release];
}

This will cause the new entry to be inserted right after the last row in the table view with the cell in column 0 (my date cell) having all contained text selected and ready for editing.

Updated: Yup. I forgot to release the new object.

Updated: Nahh… this isn’t an original idea. It is just a Cocoa/Desktop-App form of the Google 15 widget for your Google Home Page. That one has two faults; it doesn’t work in Safari (fitz is working on that) and it doesn’t work for folks that weigh themselves once a week (such as Weight Watcher participants).

Posted in Core Data, Hacks, Mac OS X, Software | 13 Comments »

Neat PyObjC Trick

Wednesday, October 19th, 2005

I demoed the latest build of PyObjC at the recent CocoaHeads meeting in Cupertino.

The demo concluded with a “show all [most, really] the tricks at once” sequence.

  • How py2app, a part of PyObjC, will automatically create an installer package from a standard Python package
  • Injecting a live Python interpreter into a running application
  • Introspecting the application
  • Interacting with Core Data, including dealing with ** style parameters
  • Modifying a managed object and having KVO automatically fire on assignment

First, grab the top-of-tree source from the pyobjc repository:

svn co http://svn.red-bean.com/pyobjc/trunk/pyobjc/

Alternatively, you can mount that URL in the finder (click cancel on all the bloody attempts to write .DS_Store files) and cp -r the source to somewhere from the Terminal.

Then:

cd pyobjc
python setup.py bdist_mpkg --open

That will build PyObjC and open an Installer package that contains the runtime, documentation, examples, and Xcode templates.

Next, grab the OutlineEdit examples from /Developer/Examples/CoreData/ and run it.

Now, from the PyObjC source directory:
Read the rest of this entry »

Posted in Cocoa, Code, Core Data, Mac OS X, PyObjC, Technology | 6 Comments »

CocoaHeads San Jose

Monday, October 10th, 2005

I will be speaking at the CocoaHeads meeting on Thursday evening at the Apple campus. In particular, I’ll be focusing on PyObjC, including integration with various Tiger specific technologies, some history, and a focus on live demonstrations of the technology.

It will be rather freeform in nature. If anyone has any particular area of interest related to Python, Cocoa, and PyObjC, let me know.

Posted in Cocoa, Core Data, Mac OS X, PyObjC, Technology | No Comments »

OutlineEdit as a PyObjC application

Monday, May 2nd, 2005

The Tiger developer tools includes several Core Data examples, including OutlineEdit which demonstrates how to manage a hierarchical object graph and display said graph in an NSOutlineView.

PyObjC contains a python version of the same application.

The example’s setup.py also demonstrates how to set up a multiple document based application that compiles an Xcode created model file and sets up an Info.plist with several registered document types.

Posted in Core Data, Mac OS X, PyObjC, Technology | No Comments »

Using Core Data from Python

Sunday, May 1st, 2005

Update #1: Putting this at the top, because it is really important. The example changed since yesterday and this now requires top-of-tree [TOT] PyObjC. In particular, all of the methods that take NSError ** parameters now take one less argument, omitting the error argument, and return a tuple where the first element of the tuple is method’s normal return value and the second element is the resulting NSError, if any.

In other words, you will either receive a tuple of the form (result, None) or a tuple of the form (None, result), but never one that has both items set or both items set to None unless there is a bug in the underlying API.

The current TOT of PyObjC adds support for automatically adjusting the signatures of any methods that take NSError ** arguments. It is less than optimal in that there is no way to pass NULL for the error argument and, therefore, no way to indicate to the underlying framework that it should not pay the potentially expensive price of instantiating and composing the contents of an NSError* instance.

Someday, that will change. But it will be a hard change to make. So, for now, we have a working solution that supports everything needed to build full featured applications with a relatively minor performance penalty in relatively odd situations (it isn’t often that you would want to call one of these methods without collecting the error information).

These changes will be in PyObjC 1.3.1.


Via PyObjC, you can write Python applications that fully take advantage of Core Data.

PyObjC fully supports KVC, KVO, and subclassing of Objective-C from Python, so use of NSManagedObject is fully enabled.

One caveat: models edited in Xcode are saved in a “source” format that is “compiled” into a binary representation as a part of building a project. A compiler is provided to do exactly that and it is called via a standard build rule as a part of Xcode’s build process.

An example would best illustrate how to manually use Core Data from Python, including compiling a model. In this example, we compile the model from the EventManager Core Data example.

First, link momc to somewhere easily accessed (this is all one line and assumes that ~/bin/ exists):

ln -s /Library/Application\ Support/Apple/Developer\ Tools/Plug-ins/XDCoreDataModel.xdplugin/Contents/Resources/momc ~/bin/momc

Then, compile the sample model and copy the CranberryFestival sample data to someplace useful:

mkdir test
cd test
momc /Developer/Examples/CoreData/EventManager/MyDocument.xcdatamodel em.mom
cp /Developer/Examples/CoreData/EventManager/Sample\ Event\ Files/CranberryFestival.events .

Now, to fire up python and work with Core Data. This assumes top of tree of PyObjC or the next production release. I ripped out the ‘>>>’ characters for copy/paste convenience. Anywhere Python normally spews something, the output shows up in italics.

First, create the managed object model (and spew a little information about an entity within):

from CoreData import *
momURL = NSURL.fileURLWithPath_("em.mom")
mom = NSManagedObjectModel.alloc().initWithContentsOfURL_(momURL)
mom.entities().valueForKey_("name")
(Event, EventParticipant, Location, Occasion, Person)
eventEntity = mom.entitiesByName()['Event']
eventEntity.attributesByName().keys()
(eventID, detailDescription, endTime, name, startTime, date)

Now, set up the persistent store coordinator and managed object context:

dataURL = NSURL.fileURLWithPath_("CranberryFestival.events")
psc = NSPersistentStoreCoordinator.alloc().initWithManagedObjectModel_(mom)
psc.addPersistentStoreWithType_configuration_URL_options_error_(None, None, dataURL, None)
(, None)
moc = NSManagedObjectContext.new()
moc.setPersistentStoreCoordinator_(psc)

Finally, fetch some Events and display some information:

fetch = NSFetchRequest.new()
fetch.setEntity_(eventEntity)
events, error = moc.executeFetchRequest_error_(fetch)
len(e)
5
for anEvent in events:
  print anEvent.valueForKey_(u'name')
Opening Ceremony
Registration
Lunch by the Bog
Pick your own Cranberries
Educational Workshop

Of course, you can always take the same approach as the Core Data Document Based Application and do everything via Interface Builder and Xcode, thus automating all of this per NSPersistentDocument.

Posted in Core Data, Mac OS X, PyObjC, Technology | No Comments »

Core Data article on ADC.

Tuesday, April 5th, 2005

There is a Core Data article available at ADC.

Cool stuff. I can’t say more, but that’ll change within the first half of 2005.

Posted in Core Data, Mac OS X, Technology | No Comments »