<?xml version="1.0" encoding="utf-8" ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><htmlxmlns="http://www.w3.org/1999/xhtml"xml:lang="en"lang="en"><head><metahttp-equiv="Content-Type"content="text/html; charset=utf-8"/><title>An introduction to PyObjC</title></head><body><h2>An introduction to PyObjC</h2><!-- :authors: Ronald Oussoren, Bob Ippolito:contact: pyobjc-dev@lists.sourceforge.net:URL: http://pyobjc.sourceforge.net/:copyright: 2003-2005 The PyObjC Project --><tableborder="1"width="80%"align="center"><tbody><tr><td><i><center>Contents</center></i><br/><ul><li><ahref="#preface">Preface</a></li><li><ahref="#first-steps">First Steps</a><ul><li><ahref="#underscores-and-lots-of-them">Underscores, and lots of them</a></li><li><ahref="#two-phase-instantiation">Two-phase instantiation</a></li><li><ahref="#objective-c-uses-accessors-everywhere">Objective-C uses accessors everywhere</a></li></ul></li><li><ahref="#objective-c-for-pyobjc-users">Objective-C for PyObjC users</a></li><li><ahref="#overview-of-the-bridge">Overview of the bridge</a><ul><li><ahref="#classes">Classes</a></li><li><ahref="#messages-and-functions">Messages and Functions</a></li><li><ahref="#reference-counting">Reference counting</a></li><li><ahref="#protocols">Protocols</a></li><li><ahref="#cocoa-bindings">Cocoa Bindings</a></li><li><ahref="#categories">Categories</a></li></ul></li><li><ahref="#accessing-python-objects-from-objective-c">Accessing Python objects from Objective-C</a></li><li><ahref="#cocoa-for-python-programmers">Cocoa for Python programmers</a></li><li><ahref="#notes-on-specific-tasks">Notes on specific tasks</a><ul><li><ahref="#working-with-threads">Working with threads</a></li><li><ahref="#finalizers">Finalizers</a></li><li><ahref="#copying">Copying</a></li></ul></li><li><ahref="#building-applications">Building applications</a><ul><li><ahref="#py2app-setup-py">&quot;py2app&quot; : setup.py</a></li><li><ahref="#ide-approach-xcode">&quot;IDE approach&quot; : Xcode</a></li></ul></li></ul></td></tr></tbody></table><h2><ahref="#id6">Preface</a></h2><p>PyObjC is a bridge between Python and Objective-C. It allows Python
scripts to use and extend existing Objective-C class libraries;
most importantly the <ahref="http://developer.apple.com/referencelibrary/API_Fundamentals/Cocoa-api-date.html">Cocoa libraries</a> by <ahref="http://www.apple.com/">Apple</a>.</p><p>This document describes how to use Objective-C class libraries from Python
scripts and how to interpret the documentation of those libraries from the
point of view of a Python programmer.</p><h2><ahref="#id7">First Steps</a></h2><p>When dealing with the Objective-C runtime, there are certain patterns
you need to learn when writing Python code. If you're not already an
Objective-C programmer, some of them will seem strange or even
&quot;un-pythonic&quot; at first. However, you will get used to it, and the way
that PyObjC works is quite compliant with the <ahref="http://www.python.org/peps/pep-0020.html">Zen of Python</a>(<code><span>import</span><span>this</span></code>). In fact, Ronald is Dutch ;)</p><p>With no further ado, here are the three most important things you
<i>must</i> know before embarking on any PyObjC voyage:</p><h3><ahref="#id8">Underscores, and lots of them</a></h3><p>Objective-C objects communicate with each other by sending messages.
The syntax for messages is somewhere in-between Python's positional and
keyword arguments. Specificlaly, Objective-C message dispatch uses
positional arguments, but parts of the message name (called &quot;selector&quot;in Objective-C terminology) are interleaved with the arguments.</p><p>An Objective-C message looks like this:</p><pre>[someObject doSomething:arg1 withSomethingElse:arg2];
</pre><p>The selector (message name) for the above snippet is this (note the colons):</p><pre>doSomething:withSomethingElse:
</pre><p>In order to have a lossless and unambiguous translation between Objective-C
messages and Python methods, the Python method name equivalent is simply
the selector with colons replaced by underscores. Since each colon in an
Objective-C selector is a placeholder for an argument, the number of
underscores in the PyObjC-ified method name is the number of arguments
that should be given.</p><p>The PyObjC translation of the above selector is (note the underscores):</p><pre>doSomething_withSomethingElse_
</pre><p>The message dispatch, translated to PyObjC, looks like this:</p><pre>someObject.doSomething_withSomethingElse_(arg1, arg2)
</pre><p><i>Methods that take one argument will have a trailing underscore</i>.</p><p>It may take a little while to get used to, but PyObjC does not ever
rename selectors. The trailing underscore will seem strange at first,
especially for cases like this:</p><pre># note the trailing underscore
someObject.setValue_(aValue)
</pre><p>There are a few additional rules regarding message dispatch, see the
<ahref="#overview-of-the-bridge">Overview of the bridge</a> for the complete rundown.</p><h3><ahref="#id9">Two-phase instantiation</a></h3><p>Objective-C, being a low-level runtime, separates the two concepts required
to instantiate an object.</p><dl><dt>allocation:</dt><dd><p>Reserve a chunk of memory large enough to hold the new object, and make
sure that all of its declared instance variables are set to &quot;zero&quot;(this means nil pointers to objects, 0 for integers, etc.).</p></dd><dt>initialization:</dt><dd><p>Fill in the blank slate allocated by the allocation phase.</p></dd></dl><p>In Objective-C, the convention is for allocation to be performed by a class
method called <code><span>alloc</span></code>, and initialization is done with method
<i>beginning with</i> the word <code><span>init</span></code>. For example, here is the syntax for
instantiating an <code><span>NSObject</span></code>:</p><pre>myObject = NSObject.alloc().init()
</pre><p>And here is an example for creating an <code><span>NSData</span></code> instance given a few bytes:</p><pre>myData = NSData.alloc().initWithBytes_length_('the bytes', 9)
</pre><p>You must also follow this convention when subclassing Objective-C classes.
When initializing, an object must always (directly or indirectly) call the
designated initializer of its <code><span>super</span></code>. The designated initializer is the
&quot;most basic&quot; initializer through which all initialization eventually ends up.
The designated initializer for <code><span>NSObject</span></code> is <code><span>init</span></code>. To find the
designated initializer for other classes, consult the documentation for that
class. Here is an example of an <code><span>NSObject</span></code> subclass with a customized
initialization phase:</p><pre>class MyClass(NSObject):
def init(self):
&quot;&quot;&quot; Designated initializer for MyClass
&quot;&quot;&quot; # ALWAYS call the super's designated initializer.
# Also, make sure to re-bind &quot;self&quot; just in case it
# returns something else, or even None!
self = super(MyClass, self).init()
if self is None: return None
self.myVariable = 10
# Unlike Python's __init__, initializers MUST return self,
# because they are allowed to return any object!
return self
class MyOtherClass(MyClass):
def initWithOtherVariable_(self, otherVariable):
&quot;&quot;&quot; Designated initializer for MyOtherClass
&quot;&quot;&quot; self = super(MyOtherClass, self).init()
if self is None: return None
self.otherVariable = otherVariable
return self
myInstance = MyClass.alloc().init()
myOtherInstance = MyOtherClass.alloc().initWithOtherVariable_(20)
</pre><p>Many Objective-C classes provide class methods that perform two-phase
instantiation for you in one step. Several examples of this are:</p><pre># This is equivalent to:
#
# myObject = NSObject.alloc().init()
#
myObject = NSObject.new()
# This is equivalent to:
#
# myDict = NSDictionary.alloc().init()
#
myDict = NSDictionary.dictionary()
# This is equivalent to:
#
# myString = NSString.alloc().initWithString_(u'my string')
#
myString = NSString.stringWithString_(u'my string')
</pre><h3><ahref="#id10">Objective-C uses accessors everywhere</a></h3><p>Unlike Python, Objective-C convention says to use accessors rather than
directly accessing instance variables of other objects. This means
that in order to access an instance variable <code><span>value</span></code> of an object
<code><span>valueContainer</span></code> you will have to use the following syntax:</p><pre># Getting
#
# notice the method call
#
myValue = valueContainer.value()
# Setting
#
# notice the naming convention and trailing underscore
#
valueContainer.setValue_(myNewValue)
</pre><p>When writing your own classes from Python, this is a bit harder since
Python only has one namespace for all attributes, even methods. If you
choose to implement accessors from Python, then you will have to name
the instance variable something else:</p><pre>class MyValueHolder(NSObject):
def initWithValue_(self, value):
self = super(MyValueHolder, self).init()
# It's recommended not to use typical Python convention here,
# as instance variables prefixed with underscores are reserved
# by the Objective-C runtime. It still works if you use
# underscores, however.
self.ivar_value = value
return self
def value(self):
return self.ivar_value
def setValue_(self, value):
self.ivar_value = value
</pre><p>It's also possible to use <ahref="http://developer.apple.com/documentation/Cocoa/Conceptual/KeyValueCoding/">Key-Value Coding</a> in some cases, which eliminates
the need for writing most accessors, but only in scenarios where the rest of
the code is using it.</p><h2><ahref="#id11">Objective-C for PyObjC users</a></h2><p>It is recommended that you take the time to understand a little bit about
Objective-C before jumping into PyObjC development. The class libraries
that you will be using from Cocoa are not documented in Python, and their
documentation will be confusing without a grasp on the semantics and syntax
of Objective-C.</p><p>Objective-C is an object-oriented programming language implemented as a
superset of C that borrows heavily in concept and syntax from Smalltalk.
of C and borrows heavily from Smalltalk. It features single inheritance with
dynamic dispatch and (in theory) multiple root classes. This is basically the
same as Python with single inheritance.</p><p>An important difference between Python and Objective-C is that the latter is
not a pure object-oriented language. Some values are not objects, but values
of plain C types, such as <code><span>int</span></code> and <code><span>double</span></code>. These basic C types can
be used as the types of arguments and the return value of methods.</p><p>Object allocation and initialization are explicit and separate actions in
Objective-C. The former is done by the class-method <code><span>alloc</span></code>, while the
latter is done by instance methods whose name customarily starts with <code><span>init</span></code>.</p><p>Objective-C code looks just like plain C code, with some easily recognizable
Smalltalk-like extensions for the object-oriented parts of the language. An
example class declaration (usually found in <code><span>.h</span></code> files) and implementation
(usually found in <code><span>.m</span></code> files) are listed below. Class declarations are easily
recognized as blocks of code between <code><span>@interface</span></code> and <code><span>@end</span></code>, and similarly
the implementation is between <code><span>@implementation</span></code> and <code><span>@end</span></code>. An expression
enclosed in brackets in Objective-C is called a message, and is the equivalent
to an instance method invocation in Python. For example, this Objective-C
code:</p><pre>[aMutableArray addObject:@&quot;constant string&quot;];
</pre><p>Is equivalent in intent to the following in Python:</p><pre>aList.append(u&quot;constant string&quot;)
</pre><p>Objective-C messages have three components: a target, a selector, and zero or
more arguments. The target, <code><span>aMutableArray</span></code>, is the object or class
receiving the message. The selector, <code><span>addObject:</span></code> uniquely identifies the
kind of message that is being sent. Finally, the arguments,
<code><span>@&quot;constant</span><span>string&quot;</span></code> are used by the implementation of the method upon
receipt of the message. The syntax of Objective-C message dispatch is
deceptively similar to keyword arguments in Python, but they are actually
quite different. Objective-C messages can not have default arguments, and all
arguments are passed in a specific order. The components of a selector may not
be reordered. Syntactically, one argument must be interleaved at every colon in
the selector. The message:</p><pre>[anArray indexOfObject:someObject inRange:someRange]
</pre><dl><dt>Target:</dt><dd><p><code><span>anArray</span></code></p></dd><dt>Selector:</dt><dd><p><code><span>indexOfObject:inRange:</span></code></p></dd><dt>Arguments:</dt><dd><p><code><span>someObject</span></code>, <code><span>someRange</span></code></p></dd></dl><p>As documented later, the straightforward translation of such a message to
Python is:</p><pre>anArray.indexOfObject_inRange_(someObject, someRange)
</pre><p>This may be awkward and &quot;unpythonic&quot; at first, however this syntax is necessary
to preserve the semantics of Objective-C message dispatch.</p><p>A class declaration:</p><pre>@interface MyClass : MySuperClass
{
id anInstanceVariable;
int anotherInstanceVariable;
}
// A class method that returns an initialized instance of this class.
// Similar to an implementation of __call__ on the metaclass.
+instanceWithObject:(id)anObject andInteger:(int)anInteger;
// An instance method, the designated initializer for MyClass.
// Similar to an implementation of __new__ on MyClass.
-initWithObject:(id)anObject andInteger:(int)anInteger;
// An accessor, instance variables (attributes) are in a separate
// namespace and are considered &quot;private&quot; in Objective-C. Conventionally,
// there is nothing similar to this in Python.
-(int)anotherInstanceVariable;
@end
</pre><p>A class implementation:</p><pre>@implementation MyClass
// Note that a type is not declared for the return value. Undeclared types
// are assumed to be &quot;id&quot;, which means any kind of instance.
+instanceWithObject:(id)anObject andInteger:(int)anInteger
{
// 1. Create an instance of MyClass.
// 2. Initialize it with its designated initializer
// &quot;initWithObject:andInteger:&quot;.
// 3. Autorelease it, so that it does not leak memory.
// 4. Return the new instance.
//
// NOTE:
// By convention,initializers (such as +new, -init, -copy)
// are the only methods that should return retained objects.
//
// NOTE:
// Since this is a class method, &quot;self&quot; refers to the class!
//
// Very roughly similar to:
// return self.__new__(anObject, anInteger)
return [[[self alloc] initWithObject:anObject andInteger:anInteger] autorelease];
}
// Note that a type is not declared for the return value. Undeclared types
// are assumed to be &quot;id&quot;, which means any kind of instance.
-initWithObject:(id)anObject andInteger:(int)anInteger
{
// Call the designated initializer of the superclass.
// Similar to:
// self = super(MyClass, self).__new__()
self = [super init];
// Bail if initialization of the superclass failed.
// Similar to:
// if self is None:
// return None
if (!self) {
return nil;
}
// Set the instance variable (attribute). The argument must be
// retained, since it will persist as long as the instance does.
// Similar to:
// # Reference counting is automatic in Python
// self.anInstanceVariable = anObject
anInstanceVariable = [anObject retain];
// Set the other instance variable. Note that since anInteger is
// a primitive &quot;C&quot; type, not an object, no reference counting takes
// place.
// Similar to:
// # Everything is an object in Python
// self.anotherInstanceVariable = anInteger
anotherInstanceVariable = anInteger;
// Like __new__ in Python, initializers in Objective-C must
// explicitly return self. Note that this is different from
// __init__.
// Similar to:
// return self
return self;
}
// an accessor, instance variables (attributes) are in a separate
// namespace and are considered &quot;private&quot;-(int)anotherInstanceVariable
{
return anotherInstanceVariable;
}
// Since objects were retained as instance variables on this object,
// they must be freed when the object is. This is similar to an
// implementation of __del__ in Python. Since Objective-C has no
// cyclic garbage collection, this isn't discouraged like it is in
// Python.
-(void)dealloc
{
// Very roughly similar to:
// del self.instanceVariable
[instanceVariable release];
// Very roughly similar to:
// super(MyClass, self).__del__()
[super dealloc];
}
@end
</pre><p>Objective-C also features exceptions, but they are typically only used for
disaster recovery, not error handling, so you will not encounter them very
often. Read <ahref="http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC/index.html">The Objective-C Programming Language</a> if you want to
know more about exceptions in Objective-C.</p><p>One thing to keep in mind when translating Objective-C snippets to Python is
that any message can be sent to <code><span>nil</span></code>, and the return value of that message
will be <code><span>nil</span></code>. PyObjC translates <code><span>nil</span></code> to <code><span>None</span></code> when crossing the
bridge, so any such attempt will raise an <code><span>AttributeError</span></code>.</p><p>For more information about Objective-C see:</p><ul><li><ahref="http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC/index.html">The Objective-C Programming Language</a> at <ahref="http://www.apple.com/">Apple</a>.</li></ul><h2><ahref="#id12">Overview of the bridge</a></h2><h3><ahref="#id13">Classes</a></h3><p>Objective-C classes are visible as (new-style) Python classes and can be
subclassed just like normal Python classes. All the usual introspection
mechanisms work as well, as do <code><span>__slots__</span></code> and descriptors. The major
differences between normal Python classes and Objective-C classes are the way
that instances are created and initialized, and the fact that Objective-C
selectors look strange when translated to Python methods.</p><p>Multiple inheritance may be used when subclassing an Objective-C class, so
long as the Objective-C class is the first base class and there is only one
Objective-C base class. The Objective-C runtime does not support multiple
inheritance. These mix-in classes should not contain different
implementations for Objective-C methods. To achieve this behavior, Categories
should be used instead.</p><p>Another thing to keep in mind is that the names of Objective-C classes must
be globally unique per process, including across Python modules. That is,
it is <i>not</i> possible to have two Python modules that define a class with the
same name. It is conventional to choose class names with a short prefix that
uniquely identify your project or company. For example, Apple uses <code><span>NS</span></code>as the prefix for all classes in the <ahref="http://developer.apple.com/referencelibrary/API_Fundamentals/Cocoa-api-date.html">Cocoa libraries</a>. Note that the <code><span>NS</span></code>prefix made much more sense when it was called NeXTstep, but persists to this
day for compatibility reasons.</p><p>As described in <ahref="#objective-c-for-pyobjc-users">Objective-C for PyObjC users</a> the creation of Objective-C
objects is a two-stage process. To initialize objects, first call a
class method to allocate the memory (typically <code><span>alloc</span></code>), and then call an
initializer (typically starts with <code><span>init</span></code>). Some classes have class methods
which perform this behind the scenes, especially classes that create cached,
immutable, or singleton instances.</p><h3><ahref="#id14">Messages and Functions</a></h3><p>Objective-C methods are bridged to Python methods. Because Objective-C
message dispatch syntax can not be translated directly to Python, a few
simple translations must take place. The rules for these translations are:</p><oltype="1"><li>Replace all colons in the selector with underscores:<blockquote><ul><li><code><span>someMethod:withFoo:andBar:</span></code> translates to <code><span>someMethod_withFoo_andBar_</span></code></li></ul></blockquote></li><li>If the result <code><span>class</span></code> or <code><span>raise</span></code> (Python keywords), append two underscores:<blockquote><ul><li><code><span>class</span></code> translates to <code><span>class__</span></code></li><li><code><span>raise</span></code> translates to <code><span>raise__</span></code></li></ul></blockquote></li><li>Use this translated selector as a normal Python method.
The arguments must be passed in the same order, and the number of
arguments passed will normally be equal to the number of underscores
in the method name; exceptions to this rule and the behavior of &quot;result&quot;are mentioned below.<blockquote><ul><li><code><span>result</span><span>=</span><span>[someObject</span><span>someMethod:firstArg</span><span>withFoo:foo</span><span>andBar:bar];</span></code>translates to
<code><span>result</span><span>=</span><span>someObject.someMethod_withFoo_andBar_(firstArg,</span><span>foo,</span><span>bar)</span></code></li></ul></blockquote></li></ol><p>Note that it is currently not possible to support methods with a variable
number of arguments from Python. These selectors must be wrapped by
custom Objective-C code in order to be accessible by Python.</p><p>Wrapped/bridged methods (and functions) have the same number of arguments
as the corresponding Objective-C method or function, unless otherwise noted
in the documentation (<ahref="api-notes-macosx.html">Notes on supported APIs and classes on Mac OS X</a> for
Cocoa on Mac OS X).</p><p>Most methods or functions that take or return pointers to values will be an
exception to this rule if it is callable from Python at all. In Objective-C
terminology, there are three kinds of pointers that can be used in a method:</p><dl><dt><code><span>in</span></code>:</dt><dd><p>Used to pass data by reference to the function. This is not a special
case from Python.</p></dd><dt><code><span>out</span></code>:</dt><dd><p>Used to pass data from the function (e.g. an additional return value).
From Python, these values will be missing from the argument list (there
will be more underscores than arguments passed). See below for notes on
how <code><span>out</span></code> arguments change the return value.</p></dd><dt><code><span>inout</span></code>:</dt><dd><p>A combination of in and out (a value is passed by reference, and mutated
upon return). Unlike <code><span>out</span></code>, these arguments remain in the argument list,
and thus do not have an effect on the number of arguments a method expects.
See below for notes on how <code><span>inout</span></code> arguments change the return value.</p></dd></dl><p>In order to determine what the return value of such an exceptional message will
look like, you must &quot;make a list&quot; of the return values with the following rules:</p><oltype="1"><li>If the return type of the method or function is not <code><span>void</span></code>, add it to the
list.</li><li>For each argument in the method or function, add it to the list if it is
<code><span>out</span></code> or <code><span>inout</span></code>.</li></ol><p>After creating this list, you will have one of three cases:</p><dl><dt>Empty:</dt><dd><p>The return value of this call will always be <code><span>None</span></code>.</p></dd><dt>One element:</dt><dd><p>The return value of this call will correspond to the one element of the list.</p></dd><dt>More than one element:</dt><dd><p>The return value of this call will be a tuple in the same order as the list.</p></dd></dl><p>The rules for pass by reference arguments may look quite complicated, but
it turns out this is very straightforward when working with them.</p><p>As an example of a method with two output arguments, <code><span>NSMatrix</span></code> implements a
selector named <code><span>getNumberOfRows:columns:</span></code> with the following signature:</p><pre>(void)getNumberOfRows:(int *)rowCount columns:(int *)columnCount
</pre><p>This method is used from Python like this:</p><pre>rowCount, columnCount = matrix.getNumberOfRows_columns_()
</pre><p>When a function or method has an array of values and the length of that array
as arguments, <code><span>None</span></code> may be passed as the length to specify that the length
of the given sequence should be used.</p><p>Python's <code><span>array.array</span></code> type may be used to represent a C array if the
typestr and size match what is expected by the selector. Numeric, numarray,
and other third party array types are not supported in PyObjC 1.3.5.</p><p>When defining methods in an Objective-C subclass, the bridge must provide
type signatures for each method to the Objective-C runtime. The default
type signature is for all arguments as well as the return value to be objects (just
like with normal Python methods). If there is no return statement in the implementation,
then the return value will be void. The bridge will automatically pick a better
signature when it has more information available. Specifically, a method overrides
an existing method, the bridge will assume you want to use the same
method signature. Furthermore, if the method is implemented in an (informal)
protocol known to the bridge it will use the signature from the corresponding
method in that signature.</p><p>The end result is that it is rarely necessary to explicitly add information about
the signature of methods. For the two most common cases where this is necessary,
we have provided convenience decorators (used like <code><span>staticmethod</span></code> or
<code><span>classmethod</span></code>):</p><dl><dt><code><span>objc.accessor</span></code>:</dt><dd><p>Use this to wrap a <ahref="http://developer.apple.com/documentation/Cocoa/Conceptual/KeyValueCoding/">Key-Value Coding</a> or <ahref="http://developer.apple.com/documentation/Cocoa/Conceptual/KeyValueObserving/">Key-Value Observing</a> compliant
accessor.</p></dd><dt><code><span>PyObjCTools.AppHelper.endSheetMethod</span></code>:</dt><dd><p>Use this to wrap the implementation of a sheet's &quot;didEndSelector&quot; callback.</p></dd></dl><p>For complete control of the mapping to Objective-C you can use the function
<code><span>objc.selector</span></code> to create custom descriptors. See the documentation of the
<code><span>objc</span></code> module for the arguments you can use with this function. It is
normally used like this:</p><pre>class MyObject(NSObject):
# -(void)someMethod:(float)arg
def someMethod_(self, arg):
pass
someMethod_ = objc.selector(someMethod_, signature='v@:f')
</pre><p>From Python 2.4, there is a decorator for this purpose:</p><pre>class MyObject(NSObject):
@objc.signature('v@:f')
def someMethod_(self, arg):
pass
</pre><h3><ahref="#id15">Reference counting</a></h3><p>The <ahref="http://developer.apple.com/referencelibrary/API_Fundamentals/Cocoa-api-date.html">Cocoa libraries</a>, and most (if not all) other class libraries for
Objective-C use explicit reference counting to manage memory. The methods
<code><span>retain</span></code>, <code><span>release</span></code> and <code><span>autorelease</span></code> are used to manage these
reference counts. You won't have to manage reference counts in Python, the
bridge does all that work for you (but see <ahref="api-notes-macosx.html">Notes on supported APIs and classes
on Mac OS X</a> for some advanced issues).</p><p>The only reasons reference counts are mentioned at all are to tell you about
ignoring them, and more importantly to introduce you to some issues w.r.t.
reference counting.</p><p>It turns out that Cocoa uses a primitive form of <ahref="http://www.python.org/doc/current/lib/module-weakref.html">weak references</a>. Those
are not true <ahref="http://www.python.org/doc/current/lib/module-weakref.html">weak references</a> as in Python, but use-cases where an object
stores a reference to another object without increasing the reference count
for that other object. The bridge cannot solve the issues this introduces
for you, which means that you get hard crashes when you're not careful when
dealing with those <ahref="http://www.python.org/doc/current/lib/module-weakref.html">weak references</a>.</p><p>The basic rule to deal with weak references is: make sure objects stays
alive as long as someone might have a weak reference to them. Due to the way
the bridge works, this means that you must make sure that you don't create
weak references from Objective-C to a plain Python object. The Python
object stays alive, but the proxy object as seen by the Objective-C code is
actually an autoreleased object that will be cleaned up unless the Objective-C
code increases its reference count.</p><p>The document <ahref="api-notes-macosx.html">Notes on supported APIs and classes on Mac OS X</a> contains
information about classes that work with weak references. The most important
are notification centers and <code><span>NSOutlineView</span></code>, to be exact: the outline view
stores weak references to the objects return by the method
<code><span>outlineView:child:ofItem:</span></code> of its data source. The easiest way to avoid
crashes with outline views is to make sure that you model for the view uses
subclasses of <code><span>NSObject</span></code> to represent the nodes in the outline view.</p><p>Another gotcha is that <code><span>obj.setDelegate_()</span></code> often does <i>not</i> retain the
delegate, so a reference should be maintained elsewhere.</p><h3><ahref="#id16">Protocols</a></h3><p>Cocoa defines a number of formal and informal protocols that specify methods
that should be implemented by a class if it is to be used in a specific role,
such as the data source for an <code><span>NSTableView</span></code>.</p><p>Those protocols are represented by instances of <code><span>objc.informal_protocol</span></code>,
and <code><span>objc.formal_protocol</span></code>. The only ones that have to care about these
objects are the maintainers of wrappers around Objective-C frameworks: they
have to keep these protocol wrappers up-to-date.</p><p>PyObjC will automatically use the information in the <code><span>informal_protocol</span></code>objects to add the right method signatures to methods, and to warn about
classes that partially implement a protocol.</p><p>See <ahref="protocols.html">PyObjC protocol support</a> for more information.</p><h3><ahref="#id17">Cocoa Bindings</a></h3><p>In Mac OS X 10.3 Apple introduced <ahref="http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaBindings/">Cocoa Bindings</a>, a method to make it easier
to create and use <i>Controller</i> objects using <ahref="http://developer.apple.com/documentation/Cocoa/Conceptual/KeyValueObserving/">Key-Value Observing</a> and
<ahref="http://developer.apple.com/documentation/Cocoa/Conceptual/KeyValueCoding/">Key-Value Coding</a>. In order to create accessors compatible with this, you
must use <code><span>objc.accessor</span></code> to create an appropriate selector descriptor.</p><p>PyObjC automaticly emits the right <ahref="http://developer.apple.com/documentation/Cocoa/Conceptual/KeyValueObserving/">Key-Value Observing</a> notifications when
you set attributes on an Objective-C class. This is however not supported for
pure python objects. You should therefore use <code><span>NSMutableArray</span></code> instances
instead of Python lists for instance variables that will be observed and contain
a sequence of values (and simularly for <code><span>NSMutableDictionary</span></code> instead of
<code><span>dict</span></code>).</p><h3><ahref="#id18">Categories</a></h3><p>Objective-C has a mechanism for modularize a class definition, it is possible
to add methods to an existing class in a separate compilation unit and even
a separate library. This mechanism is named categories and is used to enhance
existing classes, for splitting classes in several parts and to document
informal protocols.</p><p>An example of a category definition:</p><pre>@interface NSObject (MyCategory)
- (NSSize)objectFootprint;
@end
</pre><p>This declares an additional category on <code><span>NSObject</span></code>. This category contains
a single method.</p><p>The function <code><span>objc.classAddMethods</span></code> can be used to get the same effect in
Python:</p><pre>def objectFootprint(self):
pass
objc.classAddMethods(NSObject, [objectFootprint])
</pre><p>This is not very clear, PyObjC therefore also provides the following
mechanism, implemented on top of <code><span>objc.classAddMethods</span></code>:</p><pre>class NSObject(objc.Category(NSObject)):
def objectFootprint(self):
pass
</pre><p>To make it clear that <code><span>objc.Category</span></code> performs a special task the name in
the class definition must be the same as the <code><span>__name__</span></code> of the argument
to <code><span>objc.Category</span></code>.</p><h2><ahref="#id19">Accessing Python objects from Objective-C</a></h2><p>All Python objects can be accessed from Objective-C through proxy objects.
Whenever a Python object crosses the line from Python to Objective-C a proxy
object is created (of class <code><span>OC_PythonObject</span></code>, a subclass of <code><span>NSProxy</span></code>).
This proxy object will forward all method calls from Objective-C to Python, and
will return the results back to Objective-C.</p><p>See the section 'Method protocol' for a description of how PyObjC translates
between Python and Objective-C method calls.</p><p>A number of Python types/classes are treated specially:</p><ul><li>Python numbers (<code><span>int</span></code>, <code><span>float</span></code>, <code><span>long</span></code>) are translated into
<code><span>NSNumber</span></code> instances. Their identity is not preserved across the bridge.</li><li>Python <code><span>str</span></code> is proxied using <code><span>OC_PythonString</span></code>, a subclass of
<code><span>NSString</span></code>. A Python <code><span>str</span></code> may be used anywhere a <code><span>NSString</span></code> is
expected, but <code><span>unicode</span></code> should be used whenever possible.
<code><span>OC_PythonString</span></code> will use the default encoding of <code><span>NSString</span></code>, which is
normally MacRoman but could be something else.</li><li>Python <code><span>unicode</span></code> is proxied using <code><span>OC_PythonUnicode</span></code>, a subclass of
<code><span>NSString</span></code>. A Python <code><span>unicode</span></code> may be used anywhere a <code><span>NSString</span></code>is expected.</li><li>Python <code><span>dict</span></code> is proxied using <code><span>OC_PythonDictionary</span></code>, a subclass of
<code><span>NSMutableDictionary</span></code>. A Python <code><span>dict</span></code> may be used anywhere
an <code><span>NSDictionary</span></code> is expected.</li><li>Python <code><span>list</span></code> and <code><span>tuple</span></code> are proxied using <code><span>OC_PythonArray</span></code>, a
subclass of <code><span>NSMutableArray</span></code>. Python <code><span>list</span></code> or <code><span>tuple</span></code> objects
may be used anywhere an <code><span>NSArray</span></code> is expected.</li><li>Python objects that implement the Python buffer API, except for <code><span>str</span></code>and <code><span>unicode</span></code>, are proxied using <code><span>OC_PythonData</span></code>, a <code><span>NSData</span></code> subclass.
Objects that implement the Python buffer API such as <code><span>buffer</span></code>,
<code><span>array.array</span></code>, <code><span>mmap.mmap</span></code>, etc. may be used anywhere a <code><span>NSData</span></code> is
expected.</li></ul><p>These special cases allow for more transparent bridging between Python and
Objective-C.</p><h2><ahref="#id20">Cocoa for Python programmers</a></h2><p>Cocoa frameworks are mapped onto Python packages with the same name; that is
the classes, constants and functions from the AppKit framework are available
after you import <code><span>AppKit</span></code> in your Python script.</p><p>These helper modules contain <i>only</i> functions, constants and classes that
wrap items in the corresponding framework. All utility functions and classes
are located in the <code><span>PyObjCTools</span></code> package and <code><span>objc</span></code> module. Note that it
is possible to use <code><span>pydoc</span></code> (or the <code><span>help()</span></code>) function with the framework
wrappers, but that this is not very useful for the entire module due to the
size of these modules.</p><p>This makes it easier to find documentation for an item: if you import it
from the wrapper module for an Objective-C framework the documentation for
that item can be found in the documentation for the framework; otherwise the
item is documented in the PyObjC documentation.</p><p>The module <code><span>PyObjCTools.NibClassBuilder</span></code> can be used to make working with
NIB files more convenient. This module can be used to extract information
about classes from NIB files, both as a standalone tool generating source code
and during runtime. See the online documentation for this module for more
information.</p><p>PyObjC includes a number of examples that show how to use Cocoa from
Python. The <ahref="../Examples/00ReadMe.html">PyObjC Example index</a> contains an overview of those examples.</p><p>More information on Cocoa programming can be found at:</p><ul><li><ahref="http://developer.apple.com/documentation/Cocoa/Cocoa.html">Cocoa documentation at the Apple developer website</a></li><li><ahref="http://developer.apple.com/samplecode/Cocoa/index.html">Cocoa examples at the Apple developer website</a></li><li><ahref="http://www.stepwise.com/">stepwise.com</a></li><li>Your local bookstore or library</li></ul><h2><ahref="#id21">Notes on specific tasks</a></h2><h3><ahref="#id22">Working with threads</a></h3><p>Most of Cocoa, and thus PyObjC, requires an <code><span>NSAutoreleasePool</span></code> in order to function
properly. PyObjC does this automatically on the first thread it is imported from,
but other threads will require explicit <code><span>NSAutoreleasePool</span></code> management. The following
practice for working with <code><span>NSAutoreleasePool</span></code> is recommended:</p><pre>pool = NSAutoreleasePool.alloc().init()
...
del pool
</pre><p>Typically this will be done at the beginning and end of the thread. It is important
to use <code><span>del</span></code> before rebinding the <code><span>pool</span></code> local to another <code><span>NSAutoreleasePool</span></code>instance, otherwise it will not have the intended effect.</p><p>For long running threads and tight loops, it can also be useful to use this pattern
in the body of the loop in order to optimize memory usage. For example, <code><span>NSRunLoop</span></code>will be create a new <code><span>NSAutoreleasePool</span></code> at the beginning of each run loop iteration
and release it at the end.</p><h3><ahref="#id23">Finalizers</a></h3><p>In normal Python, there are two methods for writing finalizers: implementing
<code><span>__del__</span></code>, and using <code><span>weakref.ref</span></code> callbacks. Generally, <code><span>__del___</span></code> is
discouraged as it does not allow the object to participate in cyclic garbage
collection and create uncollectible garbage if not implemented properly.
<code><span>weakref.ref</span></code> callbacks avoid this restriction as they do not provide a real
reference to the object.</p><p>In Objective-C, there is no cyclic garbage collection, so all Objective-C
objects (including subclasses from Python) are already subject to these
restrictions. When subclassing an Objective-C class, you may implement
<code><span>dealloc</span></code> or <code><span>__del__</span></code>. If you implement <code><span>dealloc</span></code>, ensure that
you call the super <code><span>dealloc</span></code> at the end. If you implement both
<code><span>__del__</span></code> and <code><span>dealloc</span></code>, the order in which they are called is
undefined.</p><p>It is not currently possible to create a <code><span>weakref.ref</span></code> for any Objective-C
object. It is probably technically possible to do, but tricky, so it
may eventually be implemented in a future version of PyObjC (especially
if a future Objective-C runtime supports it).</p><h3><ahref="#id24">Copying</a></h3><p>It is possible for a Python subclass of an Objective-C class to implement
the <code><span>NSCopying</span></code> protocol. Some care must be taken when the superclass
already implements the protocol.</p><p>Some <code><span>NSCopying</span></code> compliant Objective-C classes copy the template object
manually. In those cases the Python subclass must also copy the additional
ivars manually.</p><p>Other <code><span>NSCopying</span></code> compliant Objective-C classes use a convenience function
that creates a shallow copy of the object and all of its ivars. In those
cases the Python subclass will not have to explicitly copy all of the ivars.
However, the ivars in the copy will refer to the same objects as the original,
and will thus share some state. As with shallow copies in Python, if any of
the ivars refer to mutable objects (<code><span>list</span></code>, <code><span>dict</span></code>, etc.) it may be
desirable to explicitly make shallow or deep copies of the mutable ivars.</p><p>NOTE: PyObjC might introduce a helper class when you inherit from a class
that implements <code><span>NSCopying</span></code> as an internal implementation detail.
External code should not rely on the existance of this class.</p><p>NOTE2: <code><span>SomeClass.copyWithZone_</span></code> should not be implemented unless a
superclass already implements <code><span>copyWithZone:</span></code>, or else the behavior
will be undefined (memory corruption, crashes, etc.).</p><h2><ahref="#id25">Building applications</a></h2><p>There are two different recommended ways to build applications with PyObjC.</p><h3><ahref="#id26">&quot;py2app&quot; : setup.py</a></h3><p>The PyObjC installer includes a copy of the <code><span>py2app</span></code> package. This package
offers a way to build distutils scripts for building (standalone)
applications and plugin bundles.</p><p>An example <code><span>setup.py</span></code> script:</p><pre>from distutils.core import setup
import py2app
setup(
app = [&quot;iClass.py&quot;],
data_files = [&quot;English.lproj&quot;],
)
</pre><p>During development you typically invoke it from the command line like this:</p><pre>python setup.py py2app -A
</pre><p>This will build an application bundle in a folder named <code><span>dist</span></code> in the
current folder. The <code><span>-A</span></code> option tells <code><span>py2app</span></code> to add symbolic
links for data folders and files and an Alias to your main script,
allowing you quickly rebuild the application without doing a full dependency
scan, with the additional bonus that you can edit them without rebuild. To
build a standalone application, simply do not use the <code><span>-A</span></code> option.
Note that if you are using a version of Python shipped with your operating
system, it will not be included in the application. Otherwise, your
application will include stripped down version of the Python runtime that
you ran setup.py with.</p><p>For more information about <code><span>py2app</span></code> usage, read through some of the
<code><span>setup.py</span></code> scripts used by the examples in the <ahref="../Examples/00ReadMe.txt">Examples</a> folder.
On any <code><span>setup.py</span></code> script that imports <code><span>py2app</span></code>, you can use the
following command to see the list of options:</p><pre>python setup.py py2app --help
</pre><h3><ahref="#id27">&quot;IDE approach&quot; : Xcode</a></h3><p>PyObjC includes a number of Xcode templates that can be used to
develop applications, using the same underlying functionality that
is in py2app. These templates are used like any other Xcode template,
but there are some organizational rules about the template.</p><p>See <ahref="Xcode-Templates.html">the documentation for the templates</a> for more details.</p></body></html>