pyobjc / Doc / classes.html

The branch 'pyobjc-ancient' does not exist.
<?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">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>
Python classes and Objective-C code</title>
</head>
<body>
<h2>Python classes and Objective-C code</h2>
<!-- This file is formatted using the rules for reStructuredText -->
<!-- Version 0.2 -->
<h2><a name="introduction">Introduction</a></h2>
<p>PyObjC is a proxy between Objective-C and Python and allows access to Python
classes from Objective-C and vice versa.  PyObjC also allows Python to subclass
Objective-C classes, and these subclasses will be natively visible to both runtimes.</p>
<h2><a name="accessing-python-objects-from-objective-c">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><a name="accessing-objective-c-objects-from-python">Accessing Objective-C objects from Python</a></h2>
<p>Objective-C objects are accessed through proxy objects that forward method
calls from Python to Objective-C.  All proxy objects are instances of 
<code><span>objc.objc_object</span></code>, or a subclass of this class.</p>
<p>See the section 'Method protocol' for a description of how PyObjC translates 
between Python and Objective-C method calls.</p>
<h2><a name="accessing-objective-c-classes-from-python">Accessing Objective-C classes from Python</a></h2>
<p>Objective-C classes are also accessed through proxy objects, but those are
subclasses of <code><span>objc.objc_class</span></code>.  The proxies for Objective-C classes are 
classes in Python.</p>
<p>Instances are created by calling allocator class methods (like <code><span>+alloc</span></code> or
factory methods).  Objective-C instances can not be created by using the class
as a factory function.</p>
<p>It is possible to create subclasses from Objective-C classes using the normal
mechanism.  There are some limitations though:</p>
<ol type="1">
<li>The Objective-C class must be the first base class</li>
<li>There can be only 1 Objective-C base class.
It is not possible to multiple-inherit from two Objective-C classes, this
limitation is inherited from Objective-C.</li>
<li>It is not possible to override or extend an Objective-C method using a mixin.
This is limitation will be lifted in future versions of PyObjC.</li>
<li>It is not possible to override or extend an Objective-C method by adding a
new method to the class after creating it.</li>
</ol>
<p>Limitations 3 and 4 can be worked around by creating a category using
<code><span>objc.Category</span></code>.</p>
<p>PyObjC provides support for Objective-C protocols.  The type 
<code><span>obc.informal_protocol</span></code> can be used to shadow protocol definitions in
Objective-C.  Instances of this type can be used as a superclass when defining
a subclass of an existing Objective-C class.  The information in an
'informal_protocol' object will be used to check if the new class does
implement the protocol, and to provide information to the bridge that is needed
to correctly forward methods.</p>
<p>Formal protocols are wrapped by the type <code><span>objc.formal_protocol</span></code> and can be
accessed using the function <code><span>objc.protocolNamed(...)</span></code>.  Instances of this
type can be used as a superclass when defining a subclass of an existing
Objective-C class.  The class will not be checked to see if it actually
does conform to the protocol.  Formal protocols can be created by using
<code><span>objc.formal_protocol</span></code>'s constructor.</p>
<p>A subclass of an Objective-C (proxy) class is not only a Python class, but also
an Objective-C class.  This means that it is possible to create instances of 
these classes from Objective-C using normal Objective-C syntax, although the
class must be located using the function <code><span>NSClassFromString</span></code> or equivalent
(e.g. <a href="mailto:defining``@class">defining``@class</a> MyPythonClass`` will not work).  One of the results of
this feature is that these classes can be used to implement classes that are
defined in Interface Builder NIB files.</p>
<p>Like Python classes, Objective-C classes can have instance variables.  Normal
Python instance variables in a Python subclass will only be visible from Python,
and not Objective-C (except when using Key-Value Coding).  This means that
normal Python instance variables can not be used as outlets in Interface Builder.
Objective-C visible instance variables can be defined using special properties:
<code><span>objc.ivar</span></code> and <code><span>objc.IBOutlet</span></code>.</p>
<p>The Objective-C class:</p>
<pre>
@interface MyClass : NSObject
{
  IBOutlet id my_outlet1;
  IBOutlet id my_outlet2;
  id my_ivar;
  int my_int;
}

// ...
@end // MyClass
</pre>
<p>The Python equivalent:</p>
<pre>
class MyClass(NSObject):
  my_outlet1 = objc.IBOutlet('my_outlet1')
  my_outlet2 = objc.IBOutlet('my_outlet2')
  my_ivar = objc.ivar('my_ivar')
  my_int = objc.ivar('my_int', 'i')

# ...
</pre>
<h2><a name="method-protocol">Method protocol</a></h2>
<p>There is a straightforward translation from Objective-C method names to
Python method names: Concatenate all parts of the Objective-C method name
(without any whitespace) and then replace all colons by underscores.</p>
<p>Examples:</p>
<pre>
(void)myAction:(id)sender     &lt;-&gt;     def myAction_(self, sender)
method:(int)x andY:y          &lt;-&gt;     def method_andY_(self, x, y)
</pre>
<p>As can be seen in the examples above, Objective-C allows explicit specification
of the types of arguments and the return value, while this is not possible in
Python.  This is not a problem when calling existing Objective-C methods, 
because PyObjC will automatically read the needed information from the 
Objective-C runtime, but it can be a problem when defining new Objective-C
methods in Python.</p>
<p>PyObjC therefore provides a function to define the signature of a python method
in subclasses of Objective-C classes.  This function, objc.selector, should be
used whenever defining a method that does not extend or override an existing
Objective-C method in the superclass.</p>
<p>The following Objective-C class:</p>
<pre>
@interface MyClass : NSObject
{
}

-(int)methodWithX:(int)x andY:(float)y;
-(void)myAction:(id)sender;
</pre>
<p>can be defined in Python like this:</p>
<pre>
class MyClass(NSObject):

        def methodWithX_andY_(self, x, y):
                return 0

        methodWithX_andY_ = objc.selector(methodWithX_andY_,
                signature='i@:if')

        def myAction_(self, sender):
                pass

        myAction_ = objc.selector(myAction_,
                signature='v@:')
</pre>
<p>In Python 2.4, it is also possible to write this example as such:</p>
<pre>
class MyClass(NSObject):

        @objc.signature('i@:if')
        def methodWithX_andY_(self, x, y):
                return 0

        @objc.signature('v@:')
        def myAction_(self, sender):
                pass
</pre>
<p>The explicit selectors don't really help to increase readability, especially
given the cryptic type signature strings.  It is therefore advisable to use other
methods to define the signature if possible, the most likely way to do this
is by using existing <code><span>objc.informal_protocol</span></code> definitions (like 
<code><span>AppKit.NSOutlineViewDataSource</span></code>).</p>
<p>Unless explicitly specified as above, or defined by a superclass or protocol,
PyObjC creates a default signature with an object return value, and object
arguments.  If no return statement is in the function, then the return value
is <code><span>void</span></code>, such as the above <code><span>myAction_</span></code>.  Fortunately, these cases cover
most usage of PyObjC, so it is not often necessary to explicitly define selectors
as above.</p>
</body>
</html>
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.