Archive for the 'Objective-C' Category

DPhyllotaxis

Sunday, October 25th, 2009
Screenalicious - DPhyllotaxis - 200910298 205041.539.png

Ultimately, the whole point of resurrecting my old screensaver code was to finally port DPhyllotaxis to Snow Leopard.

Beyond being, perhaps, the most over-engineered screen saver ever for what ultimately draws colored dots, I wrote this as a sort of virtual flower for my then-girlfriend, now-wife-of-more-than-a-decade, Christine.

The underlying algorithm on this one is based entirely on phyllotaxis and the phyllotactic pattern of growth seen across so much of the plant world. The most well known example being the layout of seeds in a sunflower and that particular form of phyllotaxis is exactly what this screensaver mimics.

The color calculation in this particular screen saver is, frankly, goofy. Every floret — every dot — is actually rendered. The brightness is determined by calculating a color once, grabbing the red component and then calculating the color again using a slightly different algorithm and using the previous red value as the new brightness. Rather silly, but the results are pleasant enough.

Screenalicious - DPhyllotaxis - 200910298 205114.991.png

When I originally wrote this in 1994-ish, it used Display PostScript to do all the drawing. Specifically:

/* this should not be done here */
PSarc(cp.x, cp.y, 15. + (11. * pp.r), 0, 360);
PSgsave();
PSfill();
PSgrestore();
NXSetColor(NX_COLORBLACK);
PSstroke();

I have no idea why, 15 years ago, I thought it important to note that “this should not be done here”. None. So, in the ported code, the comment is gone.

CGFloat floretDiameter = 10. + (11. * pp.r);
CGFloat floretRadius = floretDiameter / 2.;
NSRect floretRect = 
    NSMakeRect(cp.x - floretRadius,
    cp.y - floretRadius,
    floretDiameter, floretDiameter);
NSBezierPath *floretPath = [NSBezierPath 
    bezierPathWithOvalInRect: floretRect];
        
[floretPath fill];
        
[[NSColor blackColor] set];
[floretPath stroke];

There are, of course, many ways to make the above a ton faster. Save for reducing power usage by going a more efficient route, it just doesn’t matter for this particular use case as I already had to slow down the animation rate considerably.

Seems there has been a bit of performance jump between the 25MHZ 68040 this was originally written on and the 2GHZ Core 2 Duo machine I used for the porting work.

Code is in the same repository as the other screen savers. I also tossed a pre-built binary on the server. Only tested on 64-bit Snow Leopard, but it might should also work on 10.5 ppc/i386.

Class Extensions Explained

Friday, September 11th, 2009

One of the features added to Objective-C 2.0 is Class Extensions.

If you have feature requests or bugs, http://bugreport.apple.com/ is your friend!

There has been a bit of confusion about their functionality and purpose.

First, a bit of background. One of the great strengths of Objective-C is the very sharp division between interface and implementation.

Not only can you declare a public interface to a class — the set of methods that clients of the class can use — but you can also declare varying degrees of private interface ranging from “stuff for my framework” through to “stuff only to be used in the implementation of this subset of methods of the class”.

Class extensions were designed to solve two problems. The first was to enable to compiler to better validate the private interfaces a class might have and the second was to solve a subtle, but gnarly, problem with properties (another feature added to Objective-C 2.0).

Read the rest of this entry »

+initialize Can Be Executed Multiple Times (+load not so much)

Sunday, September 6th, 2009

Some confusion on StackOverflow led to a massive string of comments. This is a question that comes up often, so here is some google fodder.

In Objective-C, a class can implement +initialize. This method will be invoked the first time the class is touched, prior to any other methods (other than +load).

The documentation says:

The runtime sends initialize to each class in a program exactly one time just before the class, or any class that inherits from it, is sent its first message from within the program.

Which is exactly true. But your +initialize methods can still be executed more than once!

Specifically, if a subclass does not implement +initialize but its superclass does, then that superclass’s +initialize will be invoked once per non-implementing subclass and once for itself.

An example (Foundation Tool, Garbage Collected):

@interface Abstract: NSObject
@end
@implementation Abstract
+ (void) initialize
{
    NSLog(@"Initializing %@", self);
}

+ (void) load
{
    NSLog(@"Loading");
}
@end

@interface Sub : Abstract
@end
@implementation Sub
@end

int main (int argc, const char * argv[]) {
    [Sub class];
    return 0;
}

This will output:

ArgyBargy[3720:903] Loading
ArgyBargy[3720:903] Initializing Abstract
ArgyBargy[3720:903] Initializing Sub

Which is why most +initialize methods are implemented as:

@implementation MyClass
+ (void) initialize
{
    if (self == [MyClass class]) {
        // ... do +init stuff here ...
    }
}
...
@end

Now, categories can seriously screw things up (as usual). Namely, if you implement +initialize in a category, it will override the classes +initialize. However, a category provided +load will not; both the category’s and the class’s +load methods will be invoked.

If you were to add the following category to the Sub/Abstract/NSObject example above:

@interface Abstract(Cat)
@end
@implementation Abstract(Cat)
+ (void) load
{
    NSLog(@"Category +load");
}
+ (void) initialize
{
    NSLog(@"Category +initialize %@", self);
}
@end

The program will spew:

ArgyBargy[3919:903] Loading
ArgyBargy[3919:903] Category +load
ArgyBargy[3919:903] Category +initialize Abstract
ArgyBargy[3919:903] Category +initialize Sub

Keep in mind, as well, that the runtime sends +initialize “in a thread-safe manner”. That implies that there is a lock involved somewhere within which then also implies that you better not block on a lock in your +initialize because whoever is supposed to unlock the lock might end up blocking on +initializes lock.

Or, to put it more bluntly, do not do any heavy lifting in +initialize. Keep it super simple & fast.

For me, +initialize is to be used only as a method of last resort. Well, 2nd to last. Last resort is a constructor attributed function (or +load). Read the rest of this entry »

^ Blocks Tips & Tricks

Saturday, August 29th, 2009

Ok, I lied… next post about Blocks won’t be about the innards. At least not directly.

Having worked with Blocks for a while, I thought I’d share some tips, tricks and gotchas.

Read the rest of this entry »

Basic Blocks

Saturday, August 29th, 2009

Now that Snow Leopard has shipped, the Blocks Programming Topics is available from developer.apple.com. Go have a read; it is a great primer for Blocks.

This post is focused solely on the core syntax of Blocks; declaring a block and calling a block.

Blocks are closures for C.

That is, a block is an anonymous inline collection of code that (Note: lexical scope means function or method or {}-surrounded collection of statements:

  • has a typed argument list just like a function
  • has an inferred or declared return type
  • can capture state from the lexical scope within which it is defined
  • can optionally modify the state of the lexical scope
  • can share the potential for modification with other blocks defined within the same lexical scope
  • can continue to share and modify state defined within the lexical scope [the stack frame] after the lexical scope [the stack frame] has been destroyed

Blocks is available in GCC and Clang as shipped with the Snow Leopard Xcode developer tools. The Blocks runtime is open source and can be found within LLVM’s compiler-rt subproject repository. Blocks have also been presented to the C standards working group as N1370: Apple’s Extensions to C (which also includes Garbage Collection).

As Objective-C and C++ are both derived from C, Blocks are designed to work fine with all three languages. Thus, the syntax reflects this goal.

A block is introduced using the ^ — the caret — character. The ^ was chosen as it had no unary form (and C++ couldn’t operator overload it).

For the purposes of an excruciatingly simple example, how about a block that multiplies two numbers?

Read the rest of this entry »

AutoZone: The Objective-C Garbage Collector

Tuesday, November 11th, 2008

The source code for AutoZone, the Objective-C Garbage Collector found in Mac OS X Leopard, is now available. It has been released under the Apache v2 license.

This is the same collector that is found in Mac OS X Leopard 10.5.3 (the collector was not updated as a part of 10.5.4 or 10.5.5).

The garbage collector is not limited to Objective-C. It is actually a fairly generic scanning, conservative, generational, multi-threaded, language agnostic, collector. The implementation has certainly been tested and optimized with Mac OS X based applications.

Notably, MacRuby uses AutoZone to offer a common GC implementation across object graphs that span Ruby and Objective-C.

Objective-C: Printing Class Name from Dtrace

Saturday, January 26th, 2008

When analyzing an Objective-C application with Dtrace, one big challenge is how to introspect any objective-c objects that are passed as parameters into the various trace points.

While you can use the Objective-C provider (documented on the dtrace man page) to trace particular methods of specific classes, it doesn’t really help for actually introspecting an instance or class.

By “introspecting”, I mean “printing out the damned class name”, for example.

Full monty on the click through.

Read the rest of this entry »

Objective-C: Atomic, properties, threading and/or custom setter/getter

Sunday, January 13th, 2008

Jim Correia asked on cocoa-dev:

Can you offer any advice for the times when I must write my own accessor, but want it to have similar behaviors to the autogenerated accessor? In particular, I’m thinking about the default atomic behavior. Is this simply wrapping the work in a @synchronized(self) block? Something else?

First, some context. Jim is referring to Objective-C 2.0′s properties and, more specifically, to the behavior of methods automatically synthesized by the compiler.

By default, synthesized accessors are atomic. Atomic does not mean thread safe.

Read the rest of this entry »

Objective-C: Using Instruments to trace messages-to-nil

Friday, January 4th, 2008
In Action_tn.png

In Leopard, Apple added a new tool to the developer tool suite called Instruments. It is a timeline based debugging and performance analysis tool. With a full suite of tools to analyze all kinds of dimensions of performance, correlating all data onto a timeline that can be inspected and navigated at will. And it remembers prior runs so you can compare results before and after changes.

And it fully consumes dtrace.

Clicking through the screenshot at right will show a run of Instruments with a single analysis instrument active.

I created a custom instrument that encapsulates the dtrace script I discussed in Objective-C: Using dtrace to trace messages-to-nil.

I ran the resulting instrument against TextEdit.

What can’t be conveyed by that screenshot is exactly how “live” the data can be examined. You can click and drag on the timeline to select a subset of the run, details of the selected instrument are shown in the table in bottom right, and any given row can be selected to show the backtrace active at the time the sample was taken.

I didn’t want to clutter up the screenshot with lots of data and, thus, didn’t demonstrate the awesomeness that is being able to relate data across multiple instruments, correlated by time.

That’ll be in the next Mac OS X / Software related post.

Click on through for an explanation with screenshots as to exactly how to convert the dtrace script to an instrument.

Read the rest of this entry »

Objective-C: Using dtrace to trace messages-to-nil

Thursday, January 3rd, 2008

Update: There are [at least] two different Objective-C messagers. objc_msgSend() and objc_msgSend_stret(). All of what is written here applies to both however objc_msgSend_stret() is the problematic one when it comes to messages to nil; it is the one used to return structures and, thus, the one that does not necessarily guarantee a zero return.


In my last post on the subject, Adrian Milliner posted a short dtrace script that would log the backtrace for all invocations of objc_msgSend where the first paramater — the target — was nil.

The script is as follows:

pid$1::objc_msgSend:entry
/arg0==0/
{
  ustack();
}

Once saved to a file (in this case objc-nil-trace.d, the trace can be applied to any running Cocoa process via:

sudo dtrace -s objc-nil-trace.d <pid>

The <pid> argument should, obviously, be the process ID of the process to be traced.

It works well enough and is certainly faster than a conditional breakpoint in GDB (likely, orders of magnitude faster), but it is far from a complete solution.

Read the rest of this entry »