1========================= 2An introduction to PyObjC 3========================= 4 5.. :authors: Ronald Oussoren, Bob Ippolito 6 :contact: pyobjc-dev@lists.sourceforge.net 7 :URL: http://pyobjc.sourceforge.net/ 8 :copyright: 2003-2013 The PyObjC Project 9 10Preface 11------- 12 13PyObjC is a bridge between Python and Objective-C. It allows Python 14scripts to use and extend existing Objective-C class libraries; 15most importantly the `Cocoa libraries`_ by `Apple`_. 16 17This document describes how to use Objective-C class libraries from Python 18scripts and how to interpret the documentation of those libraries from the 19point of view of a Python programmer. 20 21.. _`Apple`: http://www.apple.com/ 22 23First Steps 24----------- 25 26When dealing with the Objective-C runtime, there are certain patterns 27you need to learn when writing Python code. If you're not already an 28Objective-C programmer, some of them will seem strange or even 29"un-pythonic" at first. However, you will get used to it, and the way 30that PyObjC works is quite compliant with the :pep:`20` (the Zen of Python, 31``import this``). In fact, Ronald is Dutch ;) 32 33With no further ado, here are the three most important things you 34*must* know before embarking on any PyObjC voyage: 35 36Underscores, and lots of them 37............................. 38 39Objective-C objects communicate with each other by sending messages. 40The syntax for messages is somewhere in-between Python's positional and 41keyword arguments. Specificlaly, Objective-C message dispatch uses 42positional arguments, but parts of the message name (called "selector" 43in Objective-C terminology) are interleaved with the arguments. 44 45An Objective-C message looks like this: 46 47 .. sourcecode:: objective-c 48 49 [someObject doSomething:arg1 withSomethingElse:arg2]; 50 51The selector (message name) for the above snippet is this (note the colons): 52 53 .. sourcecode:: objective-c 54 55 doSomething:withSomethingElse: 56 57In order to have a lossless and unambiguous translation between Objective-C 58messages and Python methods, the Python method name equivalent is simply 59the selector with colons replaced by underscores. Since each colon in an 60Objective-C selector is a placeholder for an argument, the number of 61underscores in the PyObjC-ified method name is the number of arguments 62that should be given. 63 64The PyObjC translation of the above selector is (note the underscores): 65 66 .. sourcecode:: python 67 68 doSomething_withSomethingElse_ 69 70The message dispatch, translated to PyObjC, looks like this: 71 72 .. sourcecode:: python 73 74 someObject.doSomething_withSomethingElse_(arg1, arg2) 75 76*Methods that take one argument will have a trailing underscore*. 77 78It may take a little while to get used to, but PyObjC does not ever 79rename selectors. The trailing underscore will seem strange at first, 80especially for cases like this: 81 82 .. sourcecode:: python 83 84 # note the trailing underscore 85 someObject.setValue_(aValue) 86 87There are a few additional rules regarding message dispatch, see the 88`Overview of the bridge`_ for the complete rundown. 89 90Two-phase instantiation 91....................... 92 93Objective-C, being a low-level runtime, separates the two concepts required 94to instantiate an object. 95 96allocation: 97 Reserve a chunk of memory large enough to hold the new object, and make 98 sure that all of its declared instance variables are set to "zero" 99 (this means nil pointers to objects, 0 for integers, etc.). 100 101initialization: 102 Fill in the blank slate allocated by the allocation phase. 103 104In Objective-C, the convention is for allocation to be performed by a class 105method called ``alloc``, and initialization is done with method 106*beginning with* the word ``init``. For example, here is the syntax for 107instantiating an ``NSObject``: 108 109 .. sourcecode:: python 110 111 myObject = NSObject.alloc().init() 112 113And here is an example for creating an ``NSData`` instance given a few bytes: 114 115 .. sourcecode:: python 116 117 myData = NSData.alloc().initWithBytes_length_('the bytes', 9) 118 119You must also follow this convention when subclassing Objective-C classes. 120When initializing, an object must always (directly or indirectly) call the 121designated initializer of its ``super``. The designated initializer is the 122"most basic" initializer through which all initialization eventually ends up. 123The designated initializer for ``NSObject`` is ``init``. To find the 124designated initializer for other classes, consult the documentation for that 125class. Here is an example of an ``NSObject`` subclass with a customized 126initialization phase: 127 128 .. sourcecode:: python 129 :linenos: 130 131 class MyClass(NSObject): 132 133 def init(self): 134 """ 135 Designated initializer for MyClass 136 """ 137 # ALWAYS call the super's designated initializer. 138 # Also, make sure to re-bind "self" just in case it 139 # returns something else, or even None! 140 self = super(MyClass, self).init() 141 if self is None: return None 142 143 self.myVariable = 10 144 145 # Unlike Python's __init__, initializers MUST return self, 146 # because they are allowed to return any object! 147 return self 148 149 150 class MyOtherClass(MyClass): 151 152 def initWithOtherVariable_(self, otherVariable): 153 """ 154 Designated initializer for MyOtherClass 155 """ 156 self = super(MyOtherClass, self).init() 157 if self is None: return None 158 159 self.otherVariable = otherVariable 160 return self 161 162 myInstance = MyClass.alloc().init() 163 myOtherInstance = MyOtherClass.alloc().initWithOtherVariable_(20) 164 165Many Objective-C classes provide class methods that perform two-phase 166instantiation for you in one step. Several examples of this are: 167 168 .. sourcecode:: python 169 :linenos: 170 171 # This is equivalent to: 172 # 173 # myObject = NSObject.alloc().init() 174 # 175 myObject = NSObject.new() 176 177 # This is equivalent to: 178 # 179 # myDict = NSDictionary.alloc().init() 180 # 181 myDict = NSDictionary.dictionary() 182 183 # This is equivalent to: 184 # 185 # myString = NSString.alloc().initWithString_(u'my string') 186 # 187 myString = NSString.stringWithString_(u'my string') 188 189Objective-C uses accessors everywhere 190..................................... 191 192Unlike Python, Objective-C convention says to use accessors rather than 193directly accessing instance variables of other objects. This means 194that in order to access an instance variable ``value`` of an object 195``valueContainer`` you will have to use the following syntax: 196 197 .. sourcecode:: python 198 :linenos: 199 200 # Getting 201 # 202 # notice the method call 203 # 204 myValue = valueContainer.value() 205 206 # Setting 207 # 208 # notice the naming convention and trailing underscore 209 # 210 valueContainer.setValue_(myNewValue) 211 212When writing your own classes from Python, this is a bit harder since 213Python only has one namespace for all attributes, even methods. If you 214choose to implement accessors from Python, then you will have to name 215the instance variable something else: 216 217 .. sourcecode:: python 218 :linenos: 219 220 class MyValueHolder(NSObject): 221 222 def initWithValue_(self, value): 223 self = super(MyValueHolder, self).init() 224 # It's recommended not to use typical Python convention here, 225 # as instance variables prefixed with underscores are reserved 226 # by the Objective-C runtime. It still works if you use 227 # underscores, however. 228 self.ivar_value = value 229 return self 230 231 def value(self): 232 return self.ivar_value 233 234 def setValue_(self, value): 235 self.ivar_value = value 236 237It's also possible to use `Key-Value Coding`_ in some cases, which eliminates 238the need for writing most accessors, but only in scenarios where the rest of 239the code is using it. 240 241Objective-C for PyObjC users 242---------------------------- 243 244It is recommended that you take the time to understand a little bit about 245Objective-C before jumping into PyObjC development. The class libraries 246that you will be using from Cocoa are not documented in Python, and their 247documentation will be confusing without a grasp on the semantics and syntax 248of Objective-C. 249 250Objective-C is an object-oriented programming language implemented as a 251superset of C that borrows heavily in concept and syntax from Smalltalk. 252of C and borrows heavily from Smalltalk. It features single inheritance with 253dynamic dispatch and (in theory) multiple root classes. This is basically the 254same as Python with single inheritance. 255 256An important difference between Python and Objective-C is that the latter is 257not a pure object-oriented language. Some values are not objects, but values 258of plain C types, such as ``int`` and ``double``. These basic C types can 259be used as the types of arguments and the return value of methods. 260 261Object allocation and initialization are explicit and separate actions in 262Objective-C. The former is done by the class-method ``alloc``, while the 263latter is done by instance methods whose name customarily starts with ``init``. 264 265Objective-C code looks just like plain C code, with some easily recognizable 266Smalltalk-like extensions for the object-oriented parts of the language. An 267example class declaration (usually found in ``.h`` files) and implementation 268(usually found in ``.m`` files) are listed below. Class declarations are easily 269recognized as blocks of code between ``@interface`` and ``@end``, and similarly 270the implementation is between ``@implementation`` and ``@end``. An expression 271enclosed in brackets in Objective-C is called a message, and is the equivalent 272to an instance method invocation in Python. For example, this Objective-C 273code: 274 275 .. sourcecode:: objective-c 276 277 [aMutableArray addObject:@"constant string"]; 278 279Is equivalent in intent to the following in Python: 280 281 .. sourcecode:: python 282 283 aList.append(u"constant string") 284 285Objective-C messages have three components: a target, a selector, and zero or 286more arguments. The target, ``aMutableArray``, is the object or class 287receiving the message. The selector, ``addObject:`` uniquely identifies the 288kind of message that is being sent. Finally, the arguments, 289``@"constant string"`` are used by the implementation of the method upon 290receipt of the message. The syntax of Objective-C message dispatch is 291deceptively similar to keyword arguments in Python, but they are actually 292quite different. Objective-C messages can not have default arguments, and all 293arguments are passed in a specific order. The components of a selector may not 294be reordered. Syntactically, one argument must be interleaved at every colon in 295the selector. The message: 296 297 .. sourcecode:: objective-c 298 299 [anArray indexOfObject:someObject inRange:someRange] 300 301Target: 302 ``anArray`` 303 304Selector: 305 ``indexOfObject:inRange:`` 306 307Arguments: 308 ``someObject``, ``someRange`` 309 310As documented later, the straightforward translation of such a message to 311Python is: 312 313 .. sourcecode:: python 314 315 anArray.indexOfObject_inRange_(someObject, someRange) 316 317This may be awkward and "unpythonic" at first, however this syntax is necessary 318to preserve the semantics of Objective-C message dispatch. 319 320A class declaration: 321 322 .. sourcecode:: objective-c 323 :linenos: 324 325 @interface MyClass : MySuperClass 326 { 327 id anInstanceVariable; 328 int anotherInstanceVariable; 329 } 330 331 // A class method that returns an initialized instance of this class. 332 // Similar to an implementation of __call__ on the metaclass. 333 +instanceWithObject:(id)anObject andInteger:(int)anInteger; 334 335 // An instance method, the designated initializer for MyClass. 336 // Similar to an implementation of __new__ on MyClass. 337 -initWithObject:(id)anObject andInteger:(int)anInteger; 338 339 // An accessor, instance variables (attributes) are in a separate 340 // namespace and are considered "private" in Objective-C. Conventionally, 341 // there is nothing similar to this in Python. 342 -(int)anotherInstanceVariable; 343 @end 344 345A class implementation: 346 347 .. sourcecode:: objective-c 348 :linenos: 349 350 @implementation MyClass 351 352 // Note that a type is not declared for the return value. Undeclared types 353 // are assumed to be "id", which means any kind of instance. 354 +instanceWithObject:(id)anObject andInteger:(int)anInteger 355 { 356 // 1. Create an instance of MyClass. 357 // 2. Initialize it with its designated initializer 358 // "initWithObject:andInteger:". 359 // 3. Autorelease it, so that it does not leak memory. 360 // 4. Return the new instance. 361 // 362 // NOTE: 363 // By convention,initializers (such as +new, -init, -copy) 364 // are the only methods that should return retained objects. 365 // 366 // NOTE: 367 // Since this is a class method, "self" refers to the class! 368 // 369 // Very roughly similar to: 370 // return self.__new__(anObject, anInteger) 371 return [[[self alloc] initWithObject:anObject andInteger:anInteger] autorelease]; 372 } 373 374 // Note that a type is not declared for the return value. Undeclared types 375 // are assumed to be "id", which means any kind of instance. 376 -initWithObject:(id)anObject andInteger:(int)anInteger 377 { 378 // Call the designated initializer of the superclass. 379 // Similar to: 380 // self = super(MyClass, self).__new__() 381 self = [super init]; 382 383 // Bail if initialization of the superclass failed. 384 // Similar to: 385 // if self is None: 386 // return None 387 if (!self) { 388 return nil; 389 } 390 391 // Set the instance variable (attribute). The argument must be 392 // retained, since it will persist as long as the instance does. 393 // Similar to: 394 // # Reference counting is automatic in Python 395 // self.anInstanceVariable = anObject 396 anInstanceVariable = [anObject retain]; 397 398 // Set the other instance variable. Note that since anInteger is 399 // a primitive "C" type, not an object, no reference counting takes 400 // place. 401 // Similar to: 402 // # Everything is an object in Python 403 // self.anotherInstanceVariable = anInteger 404 anotherInstanceVariable = anInteger; 405 406 // Like __new__ in Python, initializers in Objective-C must 407 // explicitly return self. Note that this is different from 408 // __init__. 409 // Similar to: 410 // return self 411 return self; 412 } 413 414 415 // an accessor, instance variables (attributes) are in a separate 416 // namespace and are considered "private" 417 -(int)anotherInstanceVariable 418 { 419 return anotherInstanceVariable; 420 } 421 422 // Since objects were retained as instance variables on this object, 423 // they must be freed when the object is. This is similar to an 424 // implementation of __del__ in Python. Since Objective-C has no 425 // cyclic garbage collection, this isn't discouraged like it is in 426 // Python. 427 -(void)dealloc 428 { 429 // Very roughly similar to: 430 // del self.instanceVariable 431 [instanceVariable release]; 432 433 // Very roughly similar to: 434 // super(MyClass, self).__del__() 435 [super dealloc]; 436 } 437 438 @end 439 440Objective-C also features exceptions, but they are typically only used for 441disaster recovery, not error handling, so you will not encounter them very 442often. Read `The Objective-C Programming Language`_ if you want to 443know more about exceptions in Objective-C. 444 445One thing to keep in mind when translating Objective-C snippets to Python is 446that any message can be sent to ``nil``, and the return value of that message 447will be ``nil``. PyObjC translates ``nil`` to ``None`` when crossing the 448bridge, so any such attempt will raise an ``AttributeError``. 449 450For more information about Objective-C see: 451 452* `The Objective-C Programming Language`_ at `Apple`_. 453 454.. _`The Objective-C Programming Language`: https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/OOP_ObjC/Introduction/Introduction.html 455 456 The link is not correct, but the actual document is not online at the moment. 457 458 459Overview of the bridge 460---------------------- 461 462Classes 463....... 464 465Objective-C classes are visible as (new-style) Python classes and can be 466subclassed just like normal Python classes. All the usual introspection 467mechanisms work as well, as do ``__slots__`` and descriptors. The major 468differences between normal Python classes and Objective-C classes are the way 469that instances are created and initialized, and the fact that Objective-C 470selectors look strange when translated to Python methods. 471 472Multiple inheritance may be used when subclassing an Objective-C class, so 473long as the Objective-C class is the first base class and there is only one 474Objective-C base class. The Objective-C runtime does not support multiple 475inheritance. These mix-in classes should not contain different 476implementations for Objective-C methods. To achieve this behavior, Categories 477should be used instead. 478 479Another thing to keep in mind is that the names of Objective-C classes must 480be globally unique per process, including across Python modules. That is, 481it is *not* possible to have two Python modules that define a class with the 482same name. It is conventional to choose class names with a short prefix that 483uniquely identify your project or company. For example, Apple uses ``NS`` 484as the prefix for all classes in the `Cocoa libraries`_. Note that the ``NS`` 485prefix made much more sense when it was called NeXTstep, but persists to this 486day for compatibility reasons. 487 488As described in `Objective-C for PyObjC users`_ the creation of Objective-C 489objects is a two-stage process. To initialize objects, first call a 490class method to allocate the memory (typically ``alloc``), and then call an 491initializer (typically starts with ``init``). Some classes have class methods 492which perform this behind the scenes, especially classes that create cached, 493immutable, or singleton instances. 494 495Messages and Functions 496...................... 497 498Objective-C methods are bridged to Python methods. Because Objective-C 499message dispatch syntax can not be translated directly to Python, a few 500simple translations must take place. The rules for these translations are: 501 5021. Replace all colons in the selector with underscores: 503 504 - ``someMethod:withFoo:andBar:`` translates to ``someMethod_withFoo_andBar_`` 505 5062. If the result ``class`` or ``raise`` (Python keywords), append two underscores: 507 508 - ``class`` translates to ``class__`` 509 - ``raise`` translates to ``raise__`` 510 5113. Use this translated selector as a normal Python method. 512 The arguments must be passed in the same order, and the number of 513 arguments passed will normally be equal to the number of underscores 514 in the method name; exceptions to this rule and the behavior of "result" 515 are mentioned below. 516 517 .. sourcecode:: objective-c 518 :linenos: 519 520 result = [someObject someMethod:firstArg withFoo:foo andBar:bar]; 521 522 translates to 523 524 .. sourcecode:: python 525 :linenos: 526 527 result = someObject.someMethod_withFoo_andBar_(firstArg, foo, bar) 528 529Note that it is currently not possible to support methods with a variable 530number of arguments from Python. These selectors must be wrapped by 531custom Objective-C code in order to be accessible by Python. 532 533Wrapped/bridged methods (and functions) have the same number of arguments 534as the corresponding Objective-C method or function, unless otherwise noted 535in the documentation (:doc:`Notes on supported APIs and classes on Mac OS X </apinotes>` for 536Cocoa on Mac OS X). 537 538Most methods or functions that take or return pointers to values will be an 539exception to this rule if it is callable from Python at all. In Objective-C 540terminology, there are three kinds of pointers that can be used in a method: 541 542``in``: 543 Used to pass data by reference to the function. This is not a special 544 case from Python. 545 546 Instead of a regular value you may also pass in the value ``objc.NULL``, 547 when you do that the Objective-C method will receive a NULL pointer instead 548 of a pointer to your value. 549 550``out``: 551 Used to pass data from the function (e.g. an additional return value). 552 553 Pass in either ``None`` or ``objc.NULL`` for output arguments. 554 to the method. If the value is ``objc.NULL`` the Objective-C code will 555 receive a NULL pointer for this argument, otherwise it will receive a 556 valid pointer. 557 558``inout``: 559 A combination of in and out (a value is passed by reference, and mutated 560 upon return). Unlike ``out``, these arguments remain in the argument list, 561 and thus do not have an effect on the number of arguments a method expects. 562 See below for notes on how ``inout`` arguments change the return value. 563 564 Instead of a regular value you may also pass in the value ``objc.NULL``, 565 when you do that the Objective-C method will receive a NULL pointer instead 566 of a pointer to your value. 567 568In order to determine what the return value of such an exceptional message will 569look like, you must "make a list" of the return values with the following rules: 570 5711. If the return type of the method or function is not ``void``, add it to the 572 list. 573 5742. For each argument in the method or function, add it to the list if it is 575 ``out`` or ``inout``. When ``objc.NULL`` was used as the argument value it 576 will also be used as the result value. 577 578After creating this list, you will have one of three cases: 579 580Empty: 581 The return value of this call will always be ``None``. 582 583One element: 584 The return value of this call will correspond to the one element of the list. 585 586More than one element: 587 The return value of this call will be a tuple in the same order as the list. 588 589The rules for pass by reference arguments may look quite complicated, but 590it turns out this is very straightforward when working with them. 591 592As an example of a method with two output arguments, ``NSMatrix`` implements a 593selector named ``getNumberOfRows:columns:`` with the following signature: 594 595 596 .. sourcecode:: objective-c 597 598 -(void)getNumberOfRows:(int *)rowCount columns:(int *)columnCount 599 600This method is used from Python like this: 601 602 .. sourcecode:: python 603 604 rowCount, columnCount = matrix.getNumberOfRows_columns_(None, None) 605 606When a function or method has an array of values and the length of that array 607as arguments, ``None`` may be passed as the length to specify that the length 608of the given sequence should be used. 609 610Python's ``array.array`` type may be used to represent a C array if the 611typestr and size match what is expected by the selector. Numeric, numarray, 612and other third party array types are not supported at the moment. 613 614When defining methods in an Objective-C subclass, the bridge must provide 615type signatures for each method to the Objective-C runtime. The default 616type signature is for all arguments as well as the return value to be objects (just 617like with normal Python methods). If there is no return statement in the implementation, 618then the return value will be void. The bridge will automatically pick a better 619signature when it has more information available. Specifically, a method overrides 620an existing method, the bridge will assume you want to use the same 621method signature. Furthermore, if the method is implemented in an (informal) 622protocol known to the bridge it will use the signature from the corresponding 623method in that signature. 624 625The end result is that it is rarely necessary to explicitly add information about 626the signature of methods. For the two most common cases where this is necessary, 627we have provided convenience decorators (used like ``staticmethod`` or 628``classmethod``): 629 630``objc.accessor``: 631 Use this to wrap a `Key-Value Coding`_ or `Key-Value Observing`_ compliant 632 accessor. 633 634``PyObjCTools.AppHelper.endSheetMethod``: 635 Use this to wrap the implementation of a sheet's "didEndSelector" callback. 636 637For complete control of the mapping to Objective-C you can use the function 638``objc.selector`` to create custom descriptors. See the documentation of the 639``objc`` module for the arguments you can use with this function. It is 640normally used like this: 641 642 .. sourcecode:: python 643 :linenos: 644 645 class MyObject(NSObject): 646 647 # -(void)someMethod:(float)arg 648 def someMethod_(self, arg): 649 pass 650 651 someMethod_ = objc.selector(someMethod_, signature='v@:f') 652 653In Python 2.4 or later there is a decorator for this purpose: 654 655 .. sourcecode:: python 656 :linenos: 657 658 class MyObject(NSObject): 659 660 @objc.signature('v@:f') 661 def someMethod_(self, arg): 662 pass 663 664 665Reference counting 666.................. 667 668The Cocoa libraries, and most (if not all) other class libraries for 669Objective-C use explicit reference counting to manage memory. The methods 670``retain``, ``release`` and ``autorelease`` are used to manage these 671reference counts. You won't have to manage reference counts in Python, the 672bridge does all that work for you (but see :doc:`Notes on supported APIs and classes 673on Mac OS X </apinotes>` for some advanced issues). 674 675The only reasons reference counts are mentioned at all are to tell you about 676ignoring them, and more importantly to introduce you to some issues w.r.t. 677reference counting. 678 679It turns out that Cocoa uses a primitive form of :mod:`weak references <weakref>`. Those 680are not true :mod:`weak references <weakref>` as in Python, but use-cases where an object 681stores a reference to another object without increasing the reference count 682for that other object. The bridge cannot solve the issues this introduces 683for you, which means that you get hard crashes when you're not careful when 684dealing with those :mod:`weak references <weakref>`. 685 686The basic rule to deal with weak references is: make sure objects stays 687alive as long as someone might have a weak reference to them. Due to the way 688the bridge works, this means that you must make sure that you don't create 689weak references from Objective-C to a plain Python object. The Python 690object stays alive, but the proxy object as seen by the Objective-C code is 691actually an autoreleased object that will be cleaned up unless the Objective-C 692code increases its reference count. 693 694The document :doc:`Notes on supported APIs and classes on Mac OS X </apinotes>` contains 695information about classes that work with weak references. The most important 696are notification centers and ``NSOutlineView``, to be exact: the outline view 697stores weak references to the objects return by the method 698``outlineView:child:ofItem:`` of its data source. The easiest way to avoid 699crashes with outline views is to make sure that you model for the view uses 700subclasses of ``NSObject`` to represent the nodes in the outline view. 701 702Another gotcha is that ``obj.setDelegate_()`` often does *not* retain the 703delegate, so a reference should be maintained elsewhere. 704 705Protocols 706......... 707 708Cocoa defines a number of formal and informal protocols that specify methods 709that should be implemented by a class if it is to be used in a specific role, 710such as the data source for an ``NSTableView``. 711 712Those protocols are represented by instances of ``objc.informal_protocol``, 713and ``objc.formal_protocol``. The only ones that have to care about these 714objects are the maintainers of wrappers around Objective-C frameworks: they 715have to keep these protocol wrappers up-to-date. 716 717PyObjC will automatically use the information in the ``informal_protocol`` 718objects to add the right method signatures to methods, and to warn about 719classes that partially implement a protocol. 720 721See :doc:`PyObjC protocol support <protocols>` for more information. 722 723Cocoa Bindings 724.............. 725 726In Mac OS X 10.3 Apple introduced `Cocoa Bindings`_, a method to make it easier 727to create and use *Controller* objects using `Key-Value Observing`_ and 728`Key-Value Coding`_. In order to create accessors compatible with this, you 729must use ``objc.accessor`` to create an appropriate selector descriptor. 730 731PyObjC automaticly emits the right `Key-Value Observing`_ notifications when 732you set attributes on an Objective-C class. This is however not supported for 733pure python objects. You should therefore use ``NSMutableArray`` instances 734instead of Python lists for instance variables that will be observed and contain 735a sequence of values (and simularly for ``NSMutableDictionary`` instead of 736``dict``). 737 738.. _`Cocoa Bindings`: https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CocoaBindings/CocoaBindings.html 739.. _`Key-Value Coding`: https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/KeyValueCoding/Articles/KeyValueCoding.html 740.. _`Key-Value Observing`: https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/KeyValueObserving/KeyValueObserving.html 741 742NOTE: Key-Value Observing is not supported for "pure" python objects, that 743is instances of classes that don't inherit from ``NSObject``. Adding such 744support is not possible adding a KVO-like interface to the Python interpreter. 745 746Categories 747.......... 748 749Objective-C has a mechanism for modularize a class definition, it is possible 750to add methods to an existing class in a separate compilation unit and even 751a separate library. This mechanism is named categories and is used to enhance 752existing classes, for splitting classes in several parts and to document 753informal protocols. 754 755An example of a category definition: 756 757 .. sourcecode:: objective-c 758 :linenos: 759 760 @interface NSObject (MyCategory) 761 - (NSSize)objectFootprint; 762 @end 763 764This declares an additional category on ``NSObject``. This category contains 765a single method. 766 767The function ``objc.classAddMethods`` can be used to get the same effect in 768Python: 769 770 .. sourcecode:: python 771 :linenos: 772 773 def objectFootprint(self): 774 pass 775 776 objc.classAddMethods(NSObject, [objectFootprint]) 777 778This is not very clear, PyObjC therefore also provides the following 779mechanism, implemented on top of ``objc.classAddMethods``: 780 781 .. sourcecode:: python 782 :linenos: 783 784 class NSObject(objc.Category(NSObject)): 785 def objectFootprint(self): 786 pass 787 788To make it clear that ``objc.Category`` performs a special task the name in 789the class definition must be the same as the ``__name__`` of the argument 790to ``objc.Category``. 791 792Accessing Python objects from Objective-C 793----------------------------------------- 794 795All Python objects can be accessed from Objective-C through proxy objects. 796Whenever a Python object crosses the line from Python to Objective-C a proxy 797object is created (of class ``OC_PythonObject``, a subclass of ``NSProxy``). 798This proxy object will forward all method calls from Objective-C to Python, and 799will return the results back to Objective-C. 800 801See the section 'Method protocol' for a description of how PyObjC translates 802between Python and Objective-C method calls. 803 804A number of Python types/classes are treated specially: 805 806- Python numbers (``int``, ``float``, ``long``) are translated into 807 ``NSNumber`` instances. Their identity is not preserved across the bridge. 808 809- Python ``str`` is proxied using ``OC_PythonString``, a subclass of 810 ``NSString``. A Python ``str`` may be used anywhere a ``NSString`` is 811 expected, but ``unicode`` should be used whenever possible. 812 ``OC_PythonString`` will use the default encoding of ``NSString``, which is 813 normally MacRoman but could be something else. 814 815- Python ``unicode`` is proxied using ``OC_PythonUnicode``, a subclass of 816 ``NSString``. A Python ``unicode`` may be used anywhere a ``NSString`` 817 is expected. 818 819- Python ``dict`` is proxied using ``OC_PythonDictionary``, a subclass of 820 ``NSMutableDictionary``. A Python ``dict`` may be used anywhere 821 an ``NSDictionary`` is expected. 822 823- Python ``list`` and ``tuple`` are proxied using ``OC_PythonArray``, a 824 subclass of ``NSMutableArray``. Python ``list`` or ``tuple`` objects 825 may be used anywhere an ``NSArray`` is expected. 826 827- Python objects that implement the Python buffer API, except for ``str`` 828 and ``unicode``, are proxied using ``OC_PythonData``, a ``NSData`` subclass. 829 Objects that implement the Python buffer API such as ``buffer``, 830 ``array.array``, ``mmap.mmap``, etc. may be used anywhere a ``NSData`` is 831 expected. 832 833These special cases allow for more transparent bridging between Python and 834Objective-C. 835 836Cocoa for Python programmers 837---------------------------- 838 839Cocoa frameworks are mapped onto Python packages with the same name; that is 840the classes, constants and functions from the AppKit framework are available 841after you import ``AppKit`` in your Python script. 842 843These helper modules contain *only* functions, constants and classes that 844wrap items in the corresponding framework. All utility functions and classes 845are located in the ``PyObjCTools`` package and ``objc`` module. Note that it 846is possible to use ``pydoc`` (or the ``help()``) function with the framework 847wrappers, but that this is not very useful for the entire module due to the 848size of these modules. 849 850This makes it easier to find documentation for an item: if you import it 851from the wrapper module for an Objective-C framework the documentation for 852that item can be found in the documentation for the framework; otherwise the 853item is documented in the PyObjC documentation. 854 855The module ``PyObjCTools.NibClassBuilder`` can be used to make working with 856NIB files more convenient. This module can be used to extract information 857about classes from NIB files, both as a standalone tool generating source code 858and during runtime. See the online documentation for this module for more 859information. 860 861PyObjC includes a number of examples that show how to use Cocoa from 862Python. The :doc:`PyObjC Example index </examples/index>` contains an overview of those examples. 863 864More information on Cocoa programming can be found at: 865 866* `Cocoa documentation at the Apple developer website`_ 867 868* `Cocoa examples at the Apple developer website`_ 869 870* Your local bookstore or library 871 872.. :doc:`PyObjC Example index </examples/index>`: 873 874.. _`Cocoa libraries`: https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CocoaFundamentals/Introduction/Introduction.html#//apple_ref/doc/uid/TP40002974 875 876.. _`Cocoa documentation at the Apple developer website`: https://developer.apple.com/library/mac/navigation/index.html#section=Frameworks&topic=Cocoa%20Layer 877 878.. _`Cocoa examples at the Apple developer website`: https://developer.apple.com/library/mac/navigation/index.html#section=Resource%20Types&topic=Sample%20Code 879 880Notes on specific tasks 881----------------------- 882 883Working with threads 884.................... 885 886Most of Cocoa, and thus PyObjC, requires an ``NSAutoreleasePool`` in order to function 887properly. PyObjC does this automatically on the first thread it is imported from, 888but other threads will require explicit ``NSAutoreleasePool`` management. The following 889practice for working with ``NSAutoreleasePool`` is recommended: 890 891 .. sourcecode:: python 892 :linenos: 893 894 pool = NSAutoreleasePool.alloc().init() 895 ... 896 del pool 897 898Typically this will be done at the beginning and end of the thread. It is important 899to use ``del`` before rebinding the ``pool`` local to another ``NSAutoreleasePool`` 900instance, otherwise it will not have the intended effect. 901 902For long running threads and tight loops, it can also be useful to use this pattern 903in the body of the loop in order to optimize memory usage. For example, ``NSRunLoop`` 904will be create a new ``NSAutoreleasePool`` at the beginning of each run loop iteration 905and release it at the end. 906 907Finalizers 908.......... 909 910In normal Python, there are two methods for writing finalizers: implementing 911``__del__``, and using ``weakref.ref`` callbacks. Generally, ``__del___`` is 912discouraged as it does not allow the object to participate in cyclic garbage 913collection and create uncollectible garbage if not implemented properly. 914``weakref.ref`` callbacks avoid this restriction as they do not provide a real 915reference to the object. 916 917In Objective-C, there is no cyclic garbage collection, so all Objective-C 918objects (including subclasses from Python) are already subject to these 919restrictions. When subclassing an Objective-C class, you may implement 920``dealloc`` or ``__del__``. If you implement ``dealloc``, ensure that 921you call the super ``dealloc`` at the end. If you implement both 922``__del__`` and ``dealloc``, the order in which they are called is 923undefined. 924 925It is not currently possible to create a ``weakref.ref`` for any Objective-C 926object. It is probably technically possible to do, but tricky, so it 927may eventually be implemented in a future version of PyObjC (especially 928if a future Objective-C runtime supports it). 929 930Copying 931....... 932 933It is possible for a Python subclass of an Objective-C class to implement 934the ``NSCopying`` protocol. Some care must be taken when the superclass 935already implements the protocol. 936 937Some ``NSCopying`` compliant Objective-C classes copy the template object 938manually. In those cases the Python subclass must also copy the additional 939ivars manually. 940 941Other ``NSCopying`` compliant Objective-C classes use a convenience function 942that creates a shallow copy of the object and all of its ivars. In those 943cases the Python subclass will not have to explicitly copy all of the ivars. 944However, the ivars in the copy will refer to the same objects as the original, 945and will thus share some state. As with shallow copies in Python, if any of 946the ivars refer to mutable objects (``list``, ``dict``, etc.) it may be 947desirable to explicitly make shallow or deep copies of the mutable ivars. 948 949NOTE: PyObjC might introduce a helper class when you inherit from a class 950that implements ``NSCopying`` as an internal implementation detail. 951External code should not rely on the existance of this class. 952 953NOTE2: ``SomeClass.copyWithZone_`` should not be implemented unless a 954superclass already implements ``copyWithZone:``, or else the behavior 955will be undefined (memory corruption, crashes, etc.). 956 957Building applications 958--------------------- 959 960There are two different recommended ways to build applications with PyObjC. 961 962"py2app" : setup.py 963.................... 964 965The PyObjC installer includes a copy of the ``py2app`` package. This package 966offers a way to build distutils scripts for building (standalone) 967applications and plugin bundles. 968 969An example ``setup.py`` script: 970 971 .. sourcecode:: python 972 :linenos: 973 974 from distutils.core import setup 975 import py2app 976 977 setup( 978 app = ["iClass.py"], 979 data_files = ["English.lproj"], 980 ) 981 982During development you typically invoke it from the command line like this: 983 984 .. sourcecode:: sh 985 986 $ python setup.py py2app -A 987 988This will build an application bundle in a folder named ``dist`` in the 989current folder. The ``-A`` option tells ``py2app`` to add symbolic 990links for data folders and files and an Alias to your main script, 991allowing you quickly rebuild the application without doing a full dependency 992scan, with the additional bonus that you can edit them without rebuild. To 993build a standalone application, simply do not use the ``-A`` option. 994Note that if you are using a version of Python shipped with your operating 995system, it will not be included in the application. Otherwise, your 996application will include stripped down version of the Python runtime that 997you ran setup.py with. 998 999For more information about ``py2app`` usage, read through some of the 1000``setup.py`` scripts used by the examples in the :doc:`Examples </examples/index>` folder. 1001On any ``setup.py`` script that imports ``py2app``, you can use the 1002following command to see the list of options: 1003 1004 .. sourcecode:: sh 1005 1006 $ python setup.py py2app --help 1007 1008 1009 1010.. 1011 This section is disabled for now because the Xcode templates aren't maintained. 1012 1013 "IDE approach" : Xcode 1014 ...................... 1015 1016 PyObjC includes a number of Xcode templates that can be used to 1017 develop applications, using the same underlying functionality that 1018 is in py2app. These templates are used like any other Xcode template, 1019 but there are some organizational rules about the template. 1020 1021 See `the documentation for the templates` for more details. 1022 1023 .. Xcode-Templates.html 1024