NSManagedObject: better than sliced bread? (Yes.)

(Update: as usual, Scott Stevenson totally kicked my ass:

+ (EPFoobarMO *)foobarWithDefaultContext
{
return [NSEntityDescription insertNewObjectForEntityForName:@"Foobar" inManagedObjectContext: [[NSApp delegate] managedObjectContext];
}

I often forget that I’m a cretin preaching to a crowd of really smart people.)

I kid you not: NSManagedObject and Core Data are becoming some of my favorite coding structures/paradigms ever. (I suppose I have Wolf Rentzsch to thank; by the way, mogenerator v1.1 is out. Check it out.) It’s just so awesome – so nice not to have to futz around with NSUndoManager, NSCoding, and all the other minutiae that some brave souls worked with in years past.

I got rejected – not just deferred, rejected – from the University of Chicago. 😦 As such, I don’t really have time to write a very lengthy entry; therefore, I’ll just leave you with this little question/guide.

The official way of instantiating an instance/subclass of NSManagedObject is (I think) to use the NSManagedObject class methodinitWithEntity:insertIntoManagedObjectContext:, like so: (we are assuming that there’s an NSManagedObjectModel and NSManagedObjectContext named model and context, respectively:

NSEntityDescription *e = [[model entitiesByName] objectForKey: @"Foobar"];
EPFoobarMO *foo = [[EPFoobarMO alloc] initWithEntity: e insertIntoManagedObjectContext: context];

Since they’re nice people, Apple gave us a convenience method:

EPFoobarMO *foo = [NSEntityDescription insertNewObjectForEntityForName: @"Foobar" inManagedObjectContext: context];

But if we’re sticking to the MVC paradigm (which we are, aren’t we?), one wants to put the initialization code for the EPFoobarMO object inside the EPFoobarMO .m/.h file.

+ (EPFoobarMO *)foobarWithContext:(NSManagedObjectContext *)context
{
// According to the docs the object returned is autoreleased
return [NSEntityDescription insertNewObjectForEntityForName:@"Foobar"
inManagedObjectContext:context];
}

But it’s ugly to have to pass the NSManagedObjectContext to the initializer every time. We could stick it inside the app’s controller:

- (EPFoobarMO *) foobar
{
return insertNewObjectForEntityForName:@"Foobar"
inManagedObjectContext:[self managedObjectContext]];
}

But that’s a flagrant violation of the MVC rules. (Of course, if you’re ignoring them, then this is an ideal solution. But down that way lies Nyarlathotep.)

Or we could resort to the insanity that is the C preprocessor. (I would give a code sample, but I don’t want to hate myself.)

Anyway, what do you think? Leave comments with your opinions or to alert me of any blatant inaccuracies.

December 27, 2006 at 4:25 am 1 comment

I got you a present!

[Update: Looks like Dave Batton beat me to the punch. *cries*]

Merry Atheist Children Get Presents Day Christmas, everyone!

In celebration of this day, I am giving you a gift – yes, a gift – from me to you. Yes, you. It is my first piece of public code – well, actually, that’s a lie. I posted this some months ago – I consider it my cleverest Java hack EVER. I’m quite proud of it. No! Digression! Must…focus. Wait…my second was this.

Anyway, it’s my third piece of public code, and I hope you like it. In short, it’s called PVCGradientCell, and it’s a subclass of NSTextFieldCell that uses the CTGradient class to mimic the Source List found in iTunes 6. It’s notable for several reasons:

  1. Despite the name of the file (PVCGradientTable) , it is actually not a subclass of NSTableView – all the code is contained in the NSTextFieldCell subclass. This is unlike Matt Gemmell’s iTableView, which requires subclassing of NSTableView. (By the way, props to Matt – his iTableView helped me fix a lot of bugs.)
  2. It uses Chad Weider’s CTGradient code to render the gradient – the majority of implementations use either stretching images or bare CoreImage code.
  3. It allows you to enable centering the text vertically, a lá Daniel Jalkut’s RSVerticallyCenteredTextCell.
  4. It allows one to specify whether the text should be bold when clicked upon.
  5. It freshens your breath.

Here’s a screenshot, with the text bolded and vertically centered:

PVCGradientScreenshot

You can grab it here, or check it out from my Subversion repository (courtesy of Assembla – great job, guys!) here:
http://tools.assembla.com/svn/importantshock

Use the username and password ‘anonymous‘ (without quotes, of course) to access the repository.

Bug reports, accolades, fame, and large sacks of cash are welcome at:

ironswallow at gmail dot etc

By the way, PVC was the initial acronym for the Cocoa application I’m working on.

Anyway, I hope that y’all have a rockin’ Christmas. Oh, and check out Scott Stevenson’s really neat THCalendarInfo present to you; it kinda owns my present in terms of complexity. (It reminds me of the Ruby linguistics module in terms of slickness and usefulness.)

Bye!

December 25, 2006 at 6:11 pm 4 comments

mogenerator, or how I nearly abandoned Core Data

Unfortunately, my Macbook Pro is out of commission due to a broken fan (I’ve sent it in to Apple; they’d better send it back soon! I’m dying here!), so I’m just going to blog about a mini-renaissance I had when working with Core Data last week.

When I first saw Core Data, I couldn’t believe my eyes. Apple’s developer tools now had a simple way to graphically model as many parts of an MVC application as possible – Interface Builder for the view, Cocoa Bindings (and custom logic) for the controller, and now Core Data for the modeling. Add in the fact that I had heard nothing but praise for it, and I was completely sold. I created the model for my application, prototyped a view, and flipped to the documentation on Core Data’s NSManagedObject.

It was, to say the least, an unpleasant surprise. Though I adored the fact that Core Data would take care of undo/redo, saving, archival formats, and saving data, I didn’t want to start using valueForKey:. setValue: forKey, primitiveValueForKey:, and setPrimitiveValue: forKey: instead of the mutator methods that I had grown to love for their combination of ease-of-use and added maintainability. Sure, I could have made a million subclasses of NSManagedObject, but the idea of doing that manually struck me as tedious – and if there’s anything I loathe, it’s tedium. And updating every object every time I made a change to the Core Data model struck me as a maintainability nightmare.

Though it may reflect poorly on me as a programmer, I considered abandoning Core Data. The magic which it brought to undo/redo/saving/archiving could not overcome the reluctance I had to view all my objects as NSManagedObjects – which, frankly, seems like quite a breach of the Model part of the MVC philosophy.

But hope lay in wait. At the bottom of some Google results about subclassing NSManagedObject, I found this page from Jonathan ‘Wolf’ Rentzsch – one of my idols, both for his coding and his vocal pro-Cocoa advocacy – about an unbelievably clever tool named mogenerator.

In short, mogenerator reads the data you have stored in an .xcdatamodel file, extracts the information about each Entity one has created, creates two subclasses of NSManagedObject for each Entity, changes the .xcdatamodel file automatically so that your Entities inherit from their proper classes, and adds code for all necessary accessor and mutator methods – in short, it removes everything I resented about Core Data.

Why two subclasses? Because if I decide to make a change to the data model, I don’t wont to worry about overwriting my own code with the automatically generated code that mogenerator creates for me. To solve this problem, Wolf has his program use one of the two files for automatically generated code, and allows one to use the second – which extends the first file’s class – for one’s own nefarious purposes. If you ever update the .xcdatamodel file, all you need to do is run mogenerator again, and only the file with the automatically generated code will be overwritten; you can be sure that the custom application logic you’ve written will stay intact.

This is a stunningly useful program, and I don’t know why people aren’t proclaiming it’s merits hither and yon. mogenerator allows one to forgo all compromise with Core Data – you get all the advantages of an NSManagedObject without sacrificing the familiar paradigm of creating specific .c/.h files for each object’s code. My thanks go out to Rentzsch for such an amazing tool.

December 19, 2006 at 6:24 pm 4 comments

It’s Hard Out Here for an MVC Advocate

Edit: I finally got the Interface Builder palette mentioned herein working. I’ll post a screenshot sometime later. I also cleared up some language.

In the past, I have alluded to the fact that I am a diehard Model-View-Controller advocate. I stay remarkably lax on other issues – I don’t mind breaking encapsulation, enjoy both static and dynamic typing, and even advocate paradigms other than OOP for certain applications. However, when it comes to GUI or web application development, I will defend Smalltalk’s Model-View-Controller paradigm to the death. In my still-inchoate Cocoa application, I’m using Interface Builder for the view, Core Data for the model, and Cocoa Bindings + my own code for the controller.

The problem emerges when I need to use the smattering of custom widgets that I’ve selected. Since creating Interface Builder palettes is so difficult, it’s hard to get people to make them – but MVC falls apart the moment you have to exit out of Interface Builder to make visual changes to your own instances of custom widgets.

Therefore, I am stuck with a hard decision. Do I break the MVC design pattern and make a zillion little subclasses of NSView, in which I stick a whole bunch of initialization code? It would be a lot easier, especially when one considers how hard it is to create an IBPalette.

But it’s so ugly! I don’t want a custom-made NSView subclass for each color CTGradient that I want! And until Chad Weider releases a CTGradientWell (please, please, please, pretty please?) making a PTGradientView will be quite difficult.

Bah. Any comments/help/IB Palettes will be appreciated.

December 6, 2006 at 5:47 pm 5 comments

Worse is Better: Python templating systems vs. Rails ERb

(Disclaimer: Python is my favorite programming language; however, I do criticize it in this article. Please redirect flames to /dev/null.)

I’ve been comparing web frameworks lately, developing a relatively simple CRUD database-backed application that can support a few bells and whistles. I’ve checked out Ruby on Rails (who hasn’t?) Django, and Turbogears in my search, and realized something as I was hacking together some templates in Kid:

Python, a far more restrictive and inflexible language – one that would seem, on the surface, to be worse for web application development than Ruby – is better for programmers, designers and security by nature of its inflexibility.

Let me explain what I mean. When designing ‘views’ – the web pages that users will see – that need to be updated with data from a given database, it is natural to break the Model-View-Controller paradigm and embed some controller logic into the application. After all, it’s so much less effort to embed

<% found_books = Book.find_all(“title = ?”, given_title) %>

into your .rhtml files then to go back into the controller file, change the return types, and make sure everything works correctly. However, Python is whitespace-sensitive, and therefore is much more difficult to embed into HTML. As such, you can’t write the mixture of Ruby and HTML that makes Rails so easy to use.

This is a good thing. I am a strong advocate of separating the model, view, and controller; by the very fact that I can’t write a combination of Python and HTML, I am forced to go back into the CherryPy/Django controller codebase and write a properly formed, secure, and elegant SQL query. Normally laxity wouldn’t bother me, but I believe that any large web application will grow into a hideous, Nylartothepic tangle if the MVC rules are not followed to the letter.

I still love Rails, but I love the templating systems in Python even more. Because Python is so restrictive, people had to write templating systems the Right Way – and that’s a good thing for everybody.

December 3, 2006 at 6:42 pm 1 comment

Fancy Windows, &c.

Lately, inspired by John Gruber‘s recent assertions that the Apple Human Interface Guidelines are no longer relevant (a good summary can be found here), the new, fancier widgets made by various Cocoa developers have come into the spotlight. Daniel Jalkut, a Very Cool Guy, developed a bunch of very nifty widgets while revamping the interface for his unbelievably cool application FlexTime, and was so kind as to blog about his thought process while doing it. His blog entry pointed me to Matt Gemmell‘s enormous stack of custom-made widgets, replete with shiny screenshots. My interest piqued, I fired up Google and found Sean Patrick O’Brien’s iLifeControls framework, a class-dumped version of Disco‘s Smoke framework, Toxic Software’s Toxic Progress Indicator and TXTableView, Chad Weider’s badging and gradient code, Blake Seely’s BSRoundedBox, Andy Matuschak’s Polished Metal buttons, AMViewAnimation, and OpenHUD framework, Andreas M.’s jaw-dropping amount of custom widgets, Erling Ellingsen’s CGSWindowWarp exposé, John Pannell’s PSMTabBarControls, Uli’s freakin’ plethora of awesome doodads, Rainer Brockerhoff’s RBSplitView, and Ankur Kothari’s CoreGraphics framework.

Wow.

(more…)

November 20, 2006 at 8:18 pm 1 comment

Adventures in Pythonic Encapsulation

Python has undergone a fair share of criticism for its lack of support for information hiding. Despite its being a solidly object-oriented language, Python has historically refused to support this facet of object-orientation. Other programming languages have implemented encapsulation in a variety of ways:

  • All variables in Smalltalk, the canonical OO language, are private; in order to access them, the programmer must write explicit accessor and mutator methods for each variable.
  • C++, Java, and C# rely on the public, private, and protected keywords in order to implement variable scoping and encapsulation.
  • Cocoa’s Objective-C code strongly encourages the programmer to use key-value coding for encapsulatory purposes.
  • Ruby does ultra-sexy encapsulation through the attr_accessor function(s).

However, Pythonistas like myself often assert that “we’re all consenting adults here.” While this attitude is refreshing in this day of slavish devotion to OOP principles, the Python community has realized that in order to avoid alienating newcomers, Python should perform some sort of encapsulatory behavior. This article intends to show the various ways in which Python supports encapsulation and/or information hiding.

(more…)

November 3, 2006 at 2:59 am 3 comments

Newer Posts


About Me



I'm Patrick Thomson. This was a blog about computer programming and computer science that I wrote in high school and college. I have since disavowed many of the views expressed on this site, but I'm keeping it around out of fondness.

If you like this, you might want to check out my Twitter or Tumblr, both of which are occasionally about code.

Blog Stats

  • 724,337 hits