• Home
  • History
  • Annotate
  • Line#
  • Navigate
  • Raw
  • Download
  • only in /macosx-10.10.1/pyobjc-45/pyobjc/pyobjc-core-2.5.1/Doc/sphinx_build/html/_sources/api/
1:mod:`objc` -- The PyObjC bridge
2================================
3
4.. module:: objc
5   :platform: MacOS X
6   :synopsis: The PyObjC bridge
7
8.. moduleauthor:: Ronald Oussoren <ronaldoussoren@mac.com>
9
10
11Introduction
12------------
13
14The module :mod:`objc` is the core of PyObjC and provides the automatic 
15bridging between Python and Objective-C. It also provides a number of
16utility functions and types that make it easier to integrate Python
17and Objective-C code.
18
19The module :mod:`objc` defines a number of functions whose names start with
20an underscore. Those functions are private and should not be used, they can
21be removed from release without warning.
22
23NOTE: This document is currently mostly an exhaustive list of stuff and 
24needs to be reorganised once I've filled in the technical details. 
25
26Debugging
27.........
28
29.. function:: setVerbose(yesOrNo)
30
31   When the argument is :const:`True` the bridge will log more information.
32
33   This currently results in output on the standard error stream whenever
34   an exception is translated from Python to Objective-C.
35
36
37.. function:: getVerbose()
38
39   Returns the current value of the verbose flag.
40
41
42Tweaking behaviour
43..................
44
45.. function:: setUseKVOForSetattr
46
47   Sets the default value for the *__useKVO__* attribute on
48   classes defined after this call. Returns the previous value.
49
50   When the *__useKVO__* attribute of a class is true instances
51   of the class will generate Key-Value Observation notifications when
52   setting attributes from Python.
53
54.. function:: setHideProtected(yesOrNo)
55
56   When the argument is :const:`True` protected methods of an Objective-C
57   class will not be included in the output of :func:`dir`. Protected methods
58   are those whose selector starts with an underscore.
59
60   This option is on by default.
61
62.. function:: setStrBridgeEnabled(yesOrNo)
63
64   If *yesOrNo* is true instances of :class:`str` are bridged
65   as NSString instances, otherwise bridging issues a :data:`PyObjCStrBridgeWarning`
66   warning and still bridges as an NSString instances.
67
68   By default PyObjC behaves as if ``setStrBridgeEnabled(True)`` was called.
69
70   .. note::
71   
72      This function is not available in Python 3.x
73
74   .. note::
75
76      Setting this option to false is discouraged and is mostly usefull when porting
77      to Python 3.
78
79.. function:: getStrBridgeEnabled
80
81   Returns :data:`True` if the str bridge is enabled and :data:`False` when it is
82   not.
83
84   .. note::
85   
86      This function is not available in Python 3.x
87
88
89Utilities
90..........
91
92.. function:: allocateBuffer(size)
93
94   Returns a writable buffer object of *size* bytes.
95
96.. function:: CFToObject
97
98   Converts an object from the standard library :mod:`CF` module to a
99   PyObjC wrapper for the same CoreFoundation object. Raises an exception
100   when the conversion fails. 
101
102   .. deprecated:: 2.4
103      part of support for the CF module in the python 2 std. library, 
104      will be removed in PyObjC 3.0.
105
106   .. note::
107      this function is not available for Python 3.
108
109
110.. function:: ObjectToCF
111
112   Converts a PyObjC wrapper for a CoreFoundation object to an object from the standard 
113   library :mod:`CF` module for the same CoreFoundation object. Raises an exception
114   when the conversion fails. 
115
116   .. deprecated:: 2.4
117      part of support for the CF module in the python 2 std. library, 
118      will be removed in PyObjC 3.0.
119
120   .. note::
121      this function is not available for Python 3.
122
123
124
125Accessing classes and protocols
126...............................
127
128.. function:: lookUpClass(classname)
129
130   :param classname: the name of an Objective-C class
131   :type classname: string
132   :return: the named Objective-C class
133   :raise: :exc:`objc.nosuchclass_error` when the class does not exist
134
135
136.. function:: getClassList()
137
138   :return: a list of a classes known to the Objective-C runtime
139
140
141.. function:: protocolsForClass(cls)
142
143   Returns a list of Protocol objects that the class claims to 
144   implement directly. The *cls* object must a subclass of NSObject.
145
146.. function:: protocolsForProcess
147
148   Returns a list of all Protocol objects known to the Objective-C
149   runtime.
150
151.. function:: propertiesForClass(objcClass)
152
153   :type objcClass: an Objective-C class or formal protocol
154   :return: a list of properties from the Objective-C runtime
155
156   The return value is a list with information about
157   properties on this class or protocol from the Objective-C runtime. This
158   does not include properties superclasses.
159
160   Every entry in the list is dictionary with the following keys:
161
162   ============= =============================================================
163   Key           Description
164   ============= =============================================================
165   *name*        Name of the property (a string)
166   ------------- -------------------------------------------------------------
167   *raw_attr*    Raw value of the attribute string (a byte string)
168   ------------- -------------------------------------------------------------
169   *typestr*     The type string for this attribute (a byte string)
170   ------------- -------------------------------------------------------------
171   *classname*   When the type string is ``objc._C_ID`` this is the
172                 name of the Objective-C class (a string).
173   ------------- -------------------------------------------------------------
174   *readonly*    True iff the property is read-only (bool)
175   ------------- -------------------------------------------------------------
176   *copy*        True iff the property is copying the value (bool)
177   ------------- -------------------------------------------------------------
178   *retain*      True iff the property is retaining the value (bool)
179   ------------- -------------------------------------------------------------
180   *nonatomic*   True iff the property is not atomic (bool)
181   ------------- -------------------------------------------------------------
182   *dynamic*     True iff the property is dynamic (bool)
183   ------------- -------------------------------------------------------------
184   *weak*        True iff the property is weak (bool)
185   ------------- -------------------------------------------------------------
186   *collectable* True iff the property is collectable (bool)
187   ------------- -------------------------------------------------------------
188   *getter*      Non-standard selector for the getter method (a byte string)
189   ------------- -------------------------------------------------------------
190   *setter*      Non-standard selector for the setter method (a byte string)
191   ============= =============================================================
192
193   All values but *name* and *raw_attr* are optional. The other attributes
194   contain a decoded version of the *raw_attr* value. The boolean attributes
195   should be interpreted as :data:`False` when the aren't present.
196
197   The documentation for the Objective-C runtime contains more information about
198   property definitions.
199
200   This function only returns information about properties as they are defined
201   in the Objective-C runtime, that is using ``@property`` definitions in an
202   Objective-C interface. Not all properties as they are commonly used  in
203   Objective-C are defined using that syntax, especially properties in classes
204   that were introduced before MacOSX 10.5.
205
206   This function always returns an empty list on MacOS X 10.4.
207
208   .. versionadded:: 2.3
209
210.. function:: listInstanceVariables(classOrInstance)
211
212   Returns a list of information about all instance variables for
213   a class or instance. *ClassOrInstance* must be a subclass of NSObject,
214   or an instance of such a class.
215
216   The elements of the list are tuples with two elements: a string with
217   the name of the instance variable and a byte string with the type encoding
218   of the instance variable.
219
220.. function:: getInstanceVariable(object, name)
221
222   Returns the value of the instance variable *name*. 
223
224   .. warning:: 
225
226      Direct access of instance variables should only be used as a debugging
227      tool and could negatively affect the invariants that a class tries to
228      maintain.
229
230.. function:: setInstanceVariable(object, name, value[ ,updateRefCounts])
231
232   Set the value of instance variable *name* to *value*. When the instance variable
233   type encoding is :data:`objc._C_ID` *updateRefCounts* must be specified and tells
234   whether or not the retainCount of the old and new values are updated.
235
236   .. warning:: 
237
238      Direct access of instance variables should only be used as a debugging
239      tool and could negatively affect the invariants that a class tries to
240      maintain.
241
242
243.. function:: protocolNamed(name)
244
245   Returns a Protocol object for the named protocol. Raises :exc:`ProtocolError`
246   when the protocol does not exist.
247
248   This is the equivalent of ``@protocol(name)`` in Objective-C.
249
250.. exception:: ProtocolError
251
252   Raised by :func:`protocolNamed` when looking up a protocol that does not
253   exist.
254
255
256Dynamic modification of classes
257...............................
258
259.. function:: classAddMethods(cls, methods)
260
261   Add a sequence of methods to the given class. 
262   
263   The effect is simular to how categories work in Objective-C. If the class
264   already implements a method that is defined in *methods* the existing
265   implementation is replaced by the new one.
266
267   The objects in *methods* should be one of:
268
269   * :class:`selector` instances with a callable (that is, the first argument
270     to :class:`selector` must not be :data:`None`).
271
272   * :class:`classmethod` or :class:`staticmethod` instances that wrap a
273     function object.
274
275   * functions
276
277   * unbound methods
278
279   For the last two the method selector is calculated using the regular
280   algoritm for this (e.g. as if ``selector(item)`` was called). The last
281   two are instance methods by default, but automaticly made class methods
282   when the class (or a superclass) has a class method with the same
283   selector.
284
285.. function:: classAddMethod(cls, name, method)
286
287   Adds function *method* as selector *name* to the given class. When *method*
288   is a selector the signature and class-method-ness are copied from the selector.
289
290   .. note::
291
292      Adding a selector that's defined in Objective-C to another class will raise
293      an exception.
294
295.. class:: Category
296
297   A helper class for adding a category to an existing Objecive-C class (subclass
298   of :c:type:`NSObject`).
299
300   Usage::
301
302       class NSObject (Category(NSObject)):
303          def method(self):
304              pass
305
306   The metaclass uses :func:`classAddMethods` to add the methods in the category
307   body to the base class.
308   
309   The name of the class must be the same as the argument to :class:`Category`.
310
311
312Plugin bundles
313..............
314
315
316.. function:: currentBundle
317
318   During module initialization this function returns an NSBundle object for
319   the current bundle. This works for application as well as plug-ins created 
320   using `py2app <http://packages.python.org/py2app>`_.
321
322   After module initialization use ``NSBundle.bundleForClass_(ClassInYourBundle)``
323   to get the bundle.
324
325.. function:: registerPlugin(pluginName)
326
327   .. deprecated:: 2.3
328      use :func:`currentBundle` instead
329
330   Register the current py2app plugin by named and return its bundle.
331
332.. function:: pluginBundle(pluginName)
333
334   .. deprecated:: 2.3
335      use :func:`currentBundle` instead
336
337   Return the main bundle for a named plugin. This should only be used
338   after it has been register with :func:`registerPlugin`.
339
340
341
342Memory management
343.................
344
345PyObjC automaticly manages Cocoa reference counts for you, the functions 
346in this section help in finetuning this behaviour.
347
348.. function:: recycleAutoreleasePool()
349
350   Flush the NSAutoreleasePool that PyObjC creates on import. Use this
351   before entering the application main loop when you do a lot of work
352   before starting the main loop.
353
354.. function:: removeAutoreleasePool()
355
356   Use this in plugin bundles to remove the release pool that PyObjC creates
357   on import. In plugins this pool will interact in unwanted ways with the
358   embedding application.
359
360
361Test support
362............
363
364The functions in this section are present as support code for PyObjC's 
365unittests and are not part of the stable API. Please let us know if you
366use these functions in your code.
367
368.. function:: splitSignature(typestring)
369
370   Split an encoded Objective-C signature string into the
371   encoding strings for seperate types.
372
373   :param typestring: an encoded method signature (byte string)
374   :return: list of type signatures
375   :type typestring: byte string
376   :rtype: list of byte strings
377
378
379.. function:: splitStructSignature(typestring)
380
381   Returns (structname, fields). *Structname* is a string or :data:`None` and
382   *fields* is a list of (name, typestr) values. The *name* is a string or
383   :data:`None` and the *typestr* is a byte string.
384
385   Raises :exc:`ValueError` when the type is not the type string for a struct
386   type.
387
388
389.. function:: repythonify(object [, type])
390
391   Internal API for converting an object to a given Objetive-C type
392   and converting it back again.
393
394
395Framework wrappers
396..................
397
398.. function:: pyobjc_id(obj)
399
400   Returns the address of the underlying object as an integer.
401
402   .. note::
403
404      This is basicly the same as :func:`id`, but for the Objective-C 
405      object wrapped by PyObjC instead of python objects.
406
407
408
409Types
410-----
411
412.. class:: objc_class
413
414   This class is the metatype for Objective-C classes and provides no user-visible
415   behavior.
416
417.. class:: objc_object
418
419   This class is the root class for Objective-C classes, that is all wrappers for
420   Objective-C classes are a subclass of this class. It is not possible to instantiate
421   instances of Objective-C classes by using the class as a callable, instances are
422   created using the standard Objective-C mechanisms instead.
423
424   .. data:: pyobjc_ISA
425
426      Read-only property that returns the current Objective-C classes of an object.
427
428   .. data:: pyobjc_instanceMethods
429
430      Read-only property that provides explicit access to just the instance methods
431      of an object.
432
433   .. data:: \__block_signature__
434
435      Property with the type signature for calling a block, or :data:`None`.
436
437   .. method:: __cobject__()
438
439      Returns a capsule object with identifier "objc.__object__" and the a reference
440      to the Objective-C object as the value.
441
442   .. method:: __reduce__()
443
444      This method ensures that Objective-C objects will not be pickled unless the subclass
445      explictly implements the pickle protocol. This is needed because the pickle will
446      write an incomplete serialization of Objective-C objects for protocol 2 or later.
447
448   .. note::
449
450      The wrapper classes for the :c:type:`NSString` class cluster aren't subclasses
451      of :class:`objc_object`, but are subclasses of the builtin :class:`unicode` type
452      (:class:`str:` in Python 3).
453
454.. class:: pyobjc_unicode
455
456   This class is used to wrap instances of the :c:type:`NSString` class cluster and is
457   a subclass of the builtin Unicode type (:class:`unicode` for python 2 and :class:`str` 
458   for Python 3).
459
460   Methods of the underlying :c:type:`NSString` class can be accessed at as methods
461   of the python type, unless they have the same name as a method of the built-in Unicode
462   type.
463
464   .. method:: nsstring
465
466      Returns an instance of a subclass of :class:`objc_object` that represents the
467      string. This provides full access to the Cocoa string API, but without easy
468      interoperability with Python APIs.
469
470
471   .. note::
472
473      Instances of :c:type:`NSString` can be mutable. Mutations to mutable Cocoa
474      strings are not reflected in instances of :class:`pyobjc_unicode`, use
475      :meth:`nsstring` and explict conversion to the built-in unicode type when
476      you work with mutable :c:type:`NSString` values.
477
478   .. note::
479
480      Cocoa strings are wrapped using a subclass of the built-in unicode string
481      to get better interaction between Python and Cocoa. Because Cocoa strings are
482      instances of the built-in unicode type they can be passed to functions in
483      extension modules that expect unicode arguments (in particular the file 
484      system access APIs such as :func:`open`).
485
486
487.. class:: selector(function[, selector[, signature[, isClassMethod[, returnType[, argumentTypes[, isRequired]]]]]])
488
489   This type is used to represent an Objective-C method. 
490
491   :param function:  The Python callable that is used for the method. Can be a :class:`classmethod` , but not a :class:`staticmethod`.
492   :param selector:  The Objective-C selector for the method. The default is calculated from the \__name__ attribute for *function*
493   :param signature: The type encoding for the method, the default signature assumes that all arguments and the result are objects
494                     (or 'void' when the function does not contain a return statement with a value).
495   :param isClassMethod: Used to specify if a method is a class method (default is :data:`True` if *function* is a :class:`classmethod`
496                     and :data:`False` otherwise)
497   :param returnType: Alternative method for specifying the method return type, using the syntax of :c:func:`Py_BuildValue`.
498   :param argumentTypes: Alternative method for specifying argument types, using the syntax of :c:func:`Py_BuildValue`.
499   :param isRequired:    Specify if the method is required (defaults to :data:`True`), used in the definition of protocols.
500
501   The arguments *returnType* and *argumentTypes* are deprecated in PyObjC 2.5, they are confusing and can only specify
502   a subset of types.
503
504   .. data:: callable
505
506      Read-only property with access to the underlying callable (the *function* argument to the constructor).
507
508   .. data:: __doc__
509
510      Documentation string for the selector
511
512   .. method:: __metadata__
513
514      Returns a copy of the metadata dictionary for the selector.  See the
515      :doc:`metadata system documentation </metadata/manual>` for more information.
516
517.. class:: ivar([name[, type[, isOutlet]]])
518
519   Creates a descriptor for accessing an Objective-C instance variable. This should only
520   be used in the definition of an Objective-C subclass, the bridge will use this information
521   to create an instance variable with the same name on the Objective-C class itself.
522
523   :param name: Name of the instance variable. The name defaults to the name the instance
524                variable is bound to in a class definition.
525
526   :param type: Type encoding for the instance varialble. Defaults to :data:`_C_ID` (that is,
527                an object)
528
529   :param isOutlet: If :data:`True` the instance variable is used as an outlet, by default
530                the instance variable is not an outlet.
531
532   .. note::
533      Sharing an ivar object between multiple class definitions is not supported.
534
535
536   Instances of :class:`ivar` have a number of attributes that help with introspection:
537   
538   * *__typestr__*: The type encoding of the Objective-C type of the variable
539
540   * *__name__*: The Objective-C name of the variable
541
542   * *__isOutlet__*: :data:`True` if the variable is an :func:`IBOutlet`
543
544   * *__isSlot__*: :data:`True` if the variable is a Python slot.
545
546   .. note::
547
548      You cannot access these attributes  through an Objective-C instance, you have to access
549      them through the class object. That's because :class:`ivar` is a data descriptor.
550
551   .. seealso::
552
553      Function :func:`IBOutlet`
554         Definition of outlets.
555
556
557.. class:: informal_protocol(name, selector_list)
558
559   This class is used to specify which methods are part of an informal protocol
560   in Objective-C. Informal protocols are a documentation construct in Objective-C and
561   as such are not present in the Objective-C runtime (as opposed to formal protocols).
562
563   Informal protocols are used by the bridge to automaticly update method signatures when
564   a class appears to implement an informal protocol. This makes it possible the define
565   a large subset of Cocoa functionality without manually setting method signatures.
566
567   :param name: Name of the protocol
568   :param selector_list: A sequence of :class:`selector` instances, all of which should have no callable.
569
570   .. data:: __name__
571
572      Read-only property with the protocol name
573
574   .. data:: selectors
575
576      Read-only property with the sequence of selectors for this protocol
577
578
579.. class:: formal_protocol(name, supers, selector_list)
580
581   This class is used to represent formal protocols in Python, and is comparabile with the
582   "@protocol" construct in Objective-C.
583
584   :param name:     The name of the protocol
585   :param supers:   A list of protocols this protocol inherits from
586   :param selector_list: A sequence of :class:`selector` instances, all of which should have no callable.
587
588   .. note::
589
590      Constructing new protocols is supported on a subset of Mac OS X platforms:
591
592      * All 32-bit programs
593
594      * 64-bit programs starting from Mac OS X 10.7, but only when PyObjC was build with
595        the 10.7 SDK (or later)
596
597   .. data:: __name__
598
599      Read-only property with the name of the protocol
600
601   .. method:: name
602
603      Returns the name of the protocol
604
605   .. method:: conformsTo_(proto)
606
607      Returns :data:`True` if this protocol conforms to protocol *proto*, returns :data:`False` otherwise.
608
609   .. method:: descriptionForInstanceMethod_(selector)
610
611      Returns a tuple with 2 byte strings: the selector name and the type signature for the selector.
612
613      Returns :data:`None` when the selector is not part of the protocol.
614
615   .. method:: descriptionForClassMethod_(selector)
616
617      Returns a tuple with 2 byte strings: the selector name and the type signature for the selector.
618
619      Returns :data:`None` when the selector is not part of the protocol.
620
621   .. method:: instanceMethods()
622
623      Returns a list of instance methods in this protocol.
624
625   .. method:: classMethods()
626
627      Returns a list of instance methods in this protocol.
628
629   .. note::
630
631      The interface of this class gives the impression that a protocol instance is an Objective-C
632      object. That was true in earlier versions of Mac OS X, but not in more recent versions.
633
634
635.. class:: varlist
636
637   A C array of unspecified length. Instances of this type cannot be created in Python code.
638
639   This type is used when the API does not specify the amount of items in an array in a way
640   that is usable by the bridge.
641
642   .. warning:: 
643
644      Access through a :class:`varlist` object can easily read beyond the end of the
645      wrapped C array.  Read the Apple documentation for APIs that return a varlist to
646      determine how many elements you can safely access.
647
648   .. method:: as_tuple(count)
649
650      Returns a tuple containing the first *count* elements of the array.
651
652   .. method:: __getitem__(index)
653    
654      Returns the value of the *index*-th element of the array. Supports numeric
655      indexes as well as slices.
656
657   .. method:: __setitem__(index, value)
658
659      Sets the value of the *index*-th element of the array. Supports numeric
660      indexes as well as slices (but assigning to a slice is only possible when
661      that does not resize the array).
662
663
664.. class:: function
665
666   Instances of this class represent global functions from Cocoa frameworks. These
667   objects are created using :func:`loadBundleFunctions` and :func:`loadFunctionList`.
668
669   .. data:: __doc__
670
671      Read-only property with the documentation string for the function.
672
673   .. data:: __name__
674
675      Read-only property with the name of the function
676
677   .. data:: __module__
678
679      Read-write property with the module that defined the function
680
681   .. method:: __metadata__
682
683      Returns a copy of the metadata dictionary for the selector.  See the
684      :doc:`metadata system documentation </metadata/manual>` for more information.
685
686
687.. class:: IMP
688
689   This class is used to represent the actual implementation of an Objective-C
690   method (basicly a C function). Instances behave the same as unbound methods:
691   you can call them but need to specify the "self" argument.
692
693   .. data:: isAlloc
694
695      Read-only attribute that specifies if the IMP is an allocator (that is,
696      the implementation of "+alloc" or one of its variant)
697
698   .. data:: isClassMethod
699
700      Read-only attribute that specified if the IMP is for a class method.
701
702   .. data:: signature
703
704      Read-only attribute with the type encoding for the IMP.
705
706   .. data:: selector
707
708      Read-only attribute with the selector for the method that this IMP
709      is associated with.
710
711   .. data:: __name__
712
713      Alias for :data:`selector`.
714
715   .. method:: __metadata__
716
717      Returns a copy of the metadata dictionary for the selector.  See the
718      :doc:`metadata system documentation </metadata/manual>` for more information.
719
720
721.. class:: super
722
723   This is a subclass of :class:`super <__builtin__.super>` that works
724   properly for Objective-C classes as well as regular Python classes.
725
726   .. note:: 
727   
728      The statement :samp:`from {Framework} import \*` will replace the 
729      built-in :class:`super <__builtin__.super>` by this class.
730
731Constants
732---------
733
734.. data:: nil
735
736   Alias for :const:`None`, for easier translation of existing Objective-C
737   code.
738
739.. data:: YES
740
741   Alias for :const:`True`, for easier translation of existing Objective-C
742   code.
743
744.. data:: NO
745
746   Alias for :const:`False`, for easier translation of existing Objective-C
747   code.
748
749.. data:: NULL
750
751   Singleton that tells the bridge to pass a :c:data:`NULL` pointer as
752   an argument when the (Objective-)C type of that argument is a pointer.
753
754   This behavior of the bridge is slightly different from using :data:`None`:
755   with :data:`None` the bridge will allocate some memory for output 
756   parameters and pass a pointer to that buffer, with :data:`NULL` the
757   bridge will always pass a :c:data:`NULL` pointer.
758
759.. data:: MAC_OS_X_VERSION_MAX_ALLOWED
760
761   The value of :c:data:`MAC_OS_X_VERSION_MAX_ALLOWED` when PyObjC was
762   compiled.
763
764.. data:: MAC_OS_X_VERSION_MIN_REQUIRED
765
766   The value of :c:data:`MAC_OS_X_VERSION_MIN_REQUIRED` when PyObjC was
767   compiled.
768
769.. data:: MAC_OS_X_VERSION_10_N
770
771   There are currently 6 constants of this form, for ``N`` from 1 to 6,
772   and these have the same value as the Objective-C constant of the same
773   name.
774 
775.. data:: platform
776
777   This always has the value "MACOSX".
778
779
780
781Objective-C type strings
782------------------------
783
784The Objective-C runtime and the PyObjC bridge represent the types of
785instance variables and methods arguments and return values as a string
786with a compact representation. The Python representation of that string is
787a byte string (that is type :class:`bytes` in Python 3.x and :class:`str`
788in Python 2.x).
789
790Basic types
791............
792
793The representation for basic types is a single character, the table below
794lists symbolic constants in the for those constants.
795
796======================== =================================================
797Name                     Objective-C type
798======================== =================================================
799:const:`_C_ID`           :c:type:`id` (an Objective-C instance)
800------------------------ ------------------------------------------------- 
801:const:`_C_CLASS`        an Objective-C class
802------------------------ -------------------------------------------------
803:const:`_C_SEL`          a method selector
804------------------------ -------------------------------------------------
805:const:`_C_CHR`          :c:type:`char`
806------------------------ -------------------------------------------------
807:const:`_C_UCHR`         :c:type:`unsigned char`
808------------------------ -------------------------------------------------
809:const:`_C_SHT`          :c:type:`short`
810------------------------ -------------------------------------------------
811:const:`_C_USHT`         :c:type:`unsigned short`
812------------------------ -------------------------------------------------
813:const:`_C_BOOL`         :c:type:`bool`  (or :c:type:`_Bool`)
814------------------------ -------------------------------------------------
815:const:`_C_INT`          :c:type:`int`
816------------------------ -------------------------------------------------
817:const:`_C_UINT`         :c:type:`unsigned int`
818------------------------ -------------------------------------------------
819:const:`_C_LNG`          :c:type:`long`
820------------------------ -------------------------------------------------
821:const:`_C_ULNG`         :c:type:`unsigned long`
822------------------------ -------------------------------------------------
823:const:`_C_LNG_LNG`      :c:type:`long long`
824------------------------ -------------------------------------------------
825:const:`_C_ULNG_LNG`     :c:type:`unsigned long long`
826------------------------ -------------------------------------------------
827:const:`_C_FLT`          :c:type:`float`
828------------------------ -------------------------------------------------
829:const:`_C_DBL`          :c:type:`double`
830------------------------ -------------------------------------------------
831:const:`_C_VOID`         :c:type:`void`
832------------------------ -------------------------------------------------
833:const:`_C_UNDEF`        "other" (such a function)
834------------------------ -------------------------------------------------
835:const:`_C_CHARPTR`      C string (:c:type:`char*`)
836------------------------ -------------------------------------------------
837:const:`_C_NSBOOL`       :c:type:`BOOL`
838------------------------ -------------------------------------------------
839:const:`_C_UNICHAR`      :c:type:`UniChar`
840------------------------ -------------------------------------------------
841:const:`_C_CHAR_AS_TEXT` :c:type:`char` when uses as text or a byte array
842------------------------ -------------------------------------------------
843:const:`_C_CHAR_AS_INT`  :c:type:`int8_t` (or :c:type:`char` when 
844                    used as a number)
845======================== =================================================
846
847The values :const:`_C_NSBOOL`, :const:`_C_UNICHAR`, :const:`_C_CHAR_AS_TEXT`
848and :const:`_C_CHAR_AS_INT` are inventions of PyObjC and are not used in
849the Objective-C runtime.
850
851Complex types
852..............
853
854More complex types can be represented using longer type strings: 
855
856* a pointer to some type is :const:`_C_PTR` followed by the type string 
857  of the pointed-to type.
858
859* a bitfield in a structure is represented as :const:`_C_BFLD` followed
860  by an integer with the number of bits. 
861  
862  Note that PyObjC cannot convert bitfields at this time.
863
864* a C structure is represented as :const:`_C_STRUCT_B` followed by the
865  struct name, followed by :const:`'='`, followed by the encoded types of
866  all fields followed by :const:`_C_STRUCT_E`. The field name (including the
867  closing equals sign) is optional.
868
869  Structures are assumed to have the default field alignment, although
870  it is possible to use a custom alignment when creating a custom type
871  for a struct using :func:`objc.createStructType`.
872
873
874* a C union is represented as :const:`_C_UNION_B` followed by the
875  struct name, followed by :const:`'='`, followed by the encoded types of
876  all fields followed by :const:`_C_UNION_E`. The field name (including the
877  closing equals sign) is optional.
878
879  Note that PyObjC cannot convert C unions at this time.
880
881* a C array is represented as :const:`_C_ARY_B` followed by an integer 
882  representing the number of items followed by the encoded element type,
883  followed by :const:`_C_ARY_E`.
884
885* The C construct 'const' is mapped to :const:`_C_CONST`, that is a 
886  :c:type:`const char*` is represented as :const:`_C_CONST` + :const:`_C_CHARPTR`.
887
888Additional annotations for method and function arguments
889........................................................
890
891Method arguments can have prefixes that closer describe their functionality.
892Those prefixes are inheritted from Distributed Objects are not used by the
893Objective-C runtime, but are used by PyObjC.
894
895* When a pointer argument is an input argument it is prefixed by
896  :const:`_C_IN`.
897
898* When a pointer argument is an output argument it is prefixed by
899  :const:`_C_OUT`.
900
901* When a pointer argument is an input and output argument it is prefixed 
902  by :const:`_C_INOUT`.
903
904* Distributed objects uses the prefix :const:`_C_BYCOPY` to tell that a 
905  value should be copied to the other side instead of sending a proxy
906  reference. This is not used by PyObjC.
907
908* Distributed objects uses the prefix :const:`_C_ONEWAY` on the method return
909  type to tell that the method result is not used and the caller should not
910  wait for a result from the other side. This is not used by PyObjC.
911
912When a pointer argument to a function prefixed by :const:`_C_IN`, 
913:const:`_C_OUT` or :const:`_C_INOUT` the brige assumes that it is a pass by
914reference argument (that is, a pointer to a single value), unless other 
915information is provided to the bridge.
916
917The :const:`_C_IN`, :const:`_C_INOUT` and :const:`_C_OUT` encodings
918correspond to the keyword ``in``, ``inout`` and ``out`` in Objective-C
919code. This can be used to add the right information to the Objective-C
920runtime without using :doc:`the metadata system </metadata/index>`. For
921example:
922
923.. sourcecode:: objective-c
924
925   @interface OCSampleClass
926
927   -(void)copyResourceOfName:(NSString*)name error:(out NSError**)error;
928
929   @end
930
931This tells the compiler that *error* is an output argument, which doesn't
932affect code generation or compiler warnings but does result in :const:`_C_OUT`
933being present in the type encoding for the argument.
934
935
936Special encoded types
937.....................
938
939The table below shows constants for a number of C types that are used 
940in Cocoa but are not basic C types.
941
942  ======================= ==============================
943  Constant                Objective-C type
944  ======================= ==============================
945  :const:`_C_CFTYPEID`    :c:type:`CFTypeID`
946  ----------------------- ------------------------------
947  :const:`_C_NSInteger`   :c:type:`NSInteger`
948  ----------------------- ------------------------------
949  :const:`_C_NSUInteger`  :c:type:`NSUInteger`
950  ----------------------- ------------------------------
951  :const:`_C_CFIndex`     :c:type:`CFIndex`
952  ----------------------- ------------------------------
953  :const:`_C_CGFloat`     :c:type:`CGFloat`
954  ----------------------- ------------------------------
955  :const:`_sockaddr_type` :c:type:`struct sockaddr`
956  ======================= ==============================
957
958
959Context pointers
960----------------
961
962A number of Objective-C APIs have one argument that is a context pointer,
963which is a :c:type:`void*`. In Objective-C your can pass a pointer to an
964arbitrary value, in Python this must be an integer.
965
966PyObjC provides a :data:`context` object that can be used to allocate
967unique integers and map those to objects.
968
969.. function:: context.register(value)
970
971   Add a value to the context registry.
972
973   :param value: An arbitrary object
974   :return: A unique integer that's suitable to be used as a context pointer
975            (the handle).
976
977.. function:: context.unregister(value):
978
979   Remove an object from the context registery, this object must be have
980   been added to the registry before.
981
982   :param value: An object in the context registry
983
984.. function:: context.get(handle)
985
986   Retrieve an object from the registry given the return value from
987   :func:`context.register`.
988
989
990Descriptors
991-----------
992
993.. function:: IBOutlet([name])
994
995   Creates an instance variable that can be used as an outlet in 
996   Interface Builder. When the name is not specified the bridge will 
997   use the name from the class dictionary.
998
999   The code block below defines an instance variable named "button" and
1000   makes that available as an outlet in Interface Builder.
1001
1002   .. code-block:: python
1003
1004      class SomeObject (NSObject):
1005
1006          button = IBOutlet()
1007
1008   .. note::
1009
1010      The IBOutlet function is recognized by Interface Builder when it
1011      reads Python code.
1012
1013.. function:: IBAction(function)
1014
1015   Mark an method as an action for use in Interface Builder.  Raises
1016   :exc:`TypeError` when the argument is not a function.
1017   
1018   Usage:
1019
1020   .. code-block:: python
1021
1022      class SomeObject (NSObject):
1023
1024         @IBAction
1025         def saveDocument_(self, sender):
1026             pass
1027
1028   .. note::
1029
1030      The IBOutlet decorator is recognized by Interface Builder when it
1031      reads Python code. Beyond that the decoerator has no effect.
1032
1033.. function:: instancemethod
1034
1035   Explicitly mark a method as an instance method. Use this when
1036   PyObjC incorrectly deduced that a method should be a class method.
1037
1038   Usage:
1039
1040   .. code-block:: python
1041
1042        class SomeObject (NSObject):
1043
1044           @instancemethod
1045           def alloc(self): 
1046               pass
1047
1048   .. note::
1049
1050      There is no function named *objc.classmethod*, use 
1051      :func:`classmethod <__builtin__.classmethod>` to explictly mark a function
1052      as a class method.
1053
1054
1055.. function:: accessor
1056
1057   Use this decorator on the definition of accessor methods to ensure
1058   that it gets the right method signature in the Objective-C runtime.
1059
1060   The conventions for accessor names that can be used with Key-Value Coding
1061   is described in the `Apple documentation for Key-Value Coding`_
1062
1063   The table below describes the convention for methods for a property named '<property>',
1064   with a short description and notes. The `Apple documentation for Key-Value Coding`_ 
1065   contains more information.
1066
1067   ================================================== =================================== =========================================
1068   Name                                               Description                         Notes
1069   ================================================== =================================== =========================================
1070   *property*                                         Getter for a basic property. 
1071   -------------------------------------------------- ----------------------------------- -----------------------------------------
1072   is\ *Property*                                     Likewise, for a boolean             PyObjC won't automaticly set the
1073                                                      property.                           correct property type, use
1074                                                                                          :func:`typeAccessor` instead of
1075                                                                                          :func:`accessor`.
1076   -------------------------------------------------- ----------------------------------- -----------------------------------------
1077   set\ *Property*\ _                                 Setter for a basic property
1078   -------------------------------------------------- ----------------------------------- -----------------------------------------
1079   countOf\ *Property*                                Returns the number of
1080                                                      items in a indexed 
1081                                                      property, or unordered
1082                                                      property
1083   -------------------------------------------------- ----------------------------------- -----------------------------------------
1084   objectIn\ *Property*\ AtIndex\_                    Returns the object at a specific 
1085                                                      index for an indexed property
1086   -------------------------------------------------- ----------------------------------- -----------------------------------------
1087   *property*\ AtIndexes\_                            Returns an array of                 Don't use this with
1088                                                      object values at specific           :func:`typedAccessor`.
1089                                                      indexes for an indexed    
1090                                                      property. The argument    
1091                                                      is an :c:type:`NSIndexSet`.
1092   -------------------------------------------------- ----------------------------------- -----------------------------------------
1093   get\ *Property*\ _range_                           Optimized accessor                  Not supported by PyObjC, don't use
1094   -------------------------------------------------- ----------------------------------- -----------------------------------------
1095   insertObject_in\ *Property*\ AtIndex\_             Add an object to an indexed 
1096                                                      property at a specific index.
1097   -------------------------------------------------- ----------------------------------- -----------------------------------------
1098   insert\ *Property*\ _atIndexes_                    Insert the values from a list of    Don't use this with 
1099                                                      at specific indices. The            :func:`typedAccessor`.
1100                                                      arguments are an :c:type:`NSArray` 
1101                                                      and an :c:type:`NSIndexSet`.
1102   -------------------------------------------------- ----------------------------------- -----------------------------------------
1103   removeObjectFrom\ *Property*\ AtIndex\_            Remove the value
1104                                                      at a specific index of an
1105                                                      indexed property.
1106   -------------------------------------------------- ----------------------------------- -----------------------------------------
1107   remove\ *Property*\ AtIndexes\_                    Remove the values at specific
1108                                                      indices of an indexed property. The 
1109                                                      argument is an 
1110                                                      :c:type:`NSIndexSet`.
1111   -------------------------------------------------- ----------------------------------- -----------------------------------------
1112   replaceObjectIn\ *Property*\ AtIndex_withObject\_  Replace the value at a specific
1113                                                      index of an indexed property.
1114   -------------------------------------------------- ----------------------------------- -----------------------------------------
1115   replace\ *Property*\ AtIndexes_with\ *Property*\_  Replace the values at specific      Don't use with :func:`typedAccessor`
1116                                                      indices of an indexed property.
1117   -------------------------------------------------- ----------------------------------- -----------------------------------------
1118   enumeratorOf\ *Property*                            Returns an :c:type:`NSEnumerator`
1119                                                       for an unordered property.
1120   -------------------------------------------------- ----------------------------------- -----------------------------------------
1121   memberOf\ *Property*\ _                             Returns True if the value is
1122                                                       a member of an unordered property
1123   -------------------------------------------------- ----------------------------------- -----------------------------------------
1124   add\ *Property*\ Object\_                           Insert a specific object in
1125                                                       an unordered property.
1126   -------------------------------------------------- ----------------------------------- -----------------------------------------
1127   add\ *Property*\ _                                  Add a set of new values
1128                                                       to an unordered property.
1129   -------------------------------------------------- ----------------------------------- -----------------------------------------
1130   remove\ *Property*\ Object\_                        Remove an object
1131                                                       from an unordered property.
1132   -------------------------------------------------- ----------------------------------- -----------------------------------------
1133   remove\ *Property*\ _                               Remove a set of objects
1134                                                       from an unordered property.
1135   -------------------------------------------------- ----------------------------------- -----------------------------------------
1136   intersect\ *Property*\ _                            Remove all objects from
1137                                                       an unorderd property that
1138                                                       are not in the set argument.
1139   -------------------------------------------------- ----------------------------------- -----------------------------------------
1140   validate\ *Property*\ _error_                       Validate the new value of a         For typed accessor's the value 
1141                                                       property                            is wrapped in an :c:type:`NSValue`
1142                                                                                           (but numbers and booleans are automaticly 
1143                                                                                           unwrapped by the bridge)
1144   ================================================== =================================== =========================================
1145
1146   PyObjC provides another mechanism for defining properties: :class:`object_property`.
1147
1148   .. versionchanged:: 2.5
1149      Added support for unordered properties. Also fixed some issues for 64-bit
1150      builds.
1151
1152.. _`Apple documentation for Key-Value Coding`: http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/KeyValueCoding/Articles/AccessorConventions.html
1153
1154.. function:: typedAccessor(valueType)
1155
1156   Use this decorator on the definition of accessor methods to ensure
1157   that it gets the right method signature in the Objective-C runtime.
1158
1159   The *valueType* is the encoded string for a single value.
1160
1161   .. note:: 
1162
1163      When you use a typed accessor you must also implement "setNilValueForKey\_",
1164      as described in the `Apple documentation for Key-Value Coding`_
1165
1166.. function:: typedSelector(signature)
1167
1168   Use this decorator to explicitly set the type signature for a method.
1169
1170   An example:
1171
1172   .. code-block:: python
1173
1174        @typedSelector(b'I@:d')
1175        def makeUnsignedIntegerOfDouble_(self, d):
1176           return d
1177   
1178
1179
1180.. function:: namedSelector(name [, signature])
1181
1182   Use this decorator to explictly set the Objective-C method name instead
1183   of deducing it from the Python name. You can optionally set the method
1184   signature as well.
1185
1186.. function:: callbackFor(callable[, argIndex=])
1187
1188   Use this decorator to tell that this function is the callback for
1189   an (Objective-C) API that stores a reference to the callback
1190   function.
1191
1192   You only *have* to use this API when the Objective-C API can store
1193   the callback function for later usage. For other functions the
1194   bridge can create a temporary callback stub.
1195
1196   Using this decorator for methods is not supported
1197
1198   Usage:
1199
1200   .. code-block:: python
1201
1202       @objc.callbackFor(NSArray.sortedArrayUsingFunction_context\_)
1203       def compare(left, right, context):
1204           return 1
1205
1206   This tells the bridge that 'compare' is used as the sort function
1207   for NSArray, and ensures that the function will get the correct
1208   Objective-C signature.
1209
1210   .. note::
1211
1212      The example will also work without the decorator because 
1213      NSArray won't store a reference to the compare function that
1214      is used after 'sortedArrayUsingFunction_context\_' returns.
1215
1216.. function:: selectorFor(callable[, argIndex])
1217
1218   Decorator to tell that this is the "callback" selector for another 
1219   API.
1220
1221   Usage:
1222
1223   .. code-block:: python
1224
1225      @objc.selectorFor(NSApplication.beginSheet_modalForWindow_modalDelegate_didEndSelector_contextInfo_) 
1226      def sheetDidEnd_returnCode_contextInfo_(self, sheet, returnCode, info): 
1227          pass 
1228      
1229   This will tell the bridge that this method is used as the end method
1230   for a sheet API, and will ensure that the method is registered with
1231   the correct Objective-C signature.
1232
1233
1234.. function:: synthesize(name[, copy[, readwrite[, type[, ivarName]]]])
1235
1236   :param name:  name of the property
1237   :param copy:  if false (default) values are stored as is, otherwise
1238                 new values are copied.
1239   :param readwrite: If true (default) the property is read-write
1240   :param type:  an encoded type for the property, defaults to 
1241                 :data:`_C_ID`.
1242   :param iVarName: Name of the instance variable used to store
1243                    the value. Default to the name of the property
1244                    prefixed by and underscore.
1245
1246   This synthensizes a getter, and if necessary, setter method with
1247   the correct signature. The getter and setter provide access to
1248   an instance variable.
1249
1250   This can be used when specific semantics are required (such as
1251   copying values before storing them).
1252
1253   The class :class:`object_property` provides simular features with
1254   a nicer python interface: with that calss the property behaves
1255   itself like a property for python code, with this function you
1256   still have to call accessor methods in your code.
1257
1258Interacting with ``@synchronized`` blocks
1259-----------------------------------------
1260
1261PyObjC provides an API that implements locking in the same way as the
1262``@synchronized`` statement in Objective-C.
1263
1264.. code-block:: python
1265
1266  with object_lock(anNSObject):
1267      pass
1268
1269.. class:: object_lock(value)
1270
1271   This class represents the mutex that protects an Objective-C object
1272   for the ``@synchronized`` statement. This can be used as a context
1273   manager for the ``with`` statement, but can also be used standalone.
1274
1275   .. method:: lock
1276
1277      Acquire the object mutex
1278
1279   .. method:: unlock
1280
1281      Release the object mutex
1282
1283
1284Archiving Python and Objective-C objects
1285----------------------------------------
1286
1287Python and Objective-C each provide a native object serialization method,
1288the :mod:`pickle` module in Python and the :c:type:`NSCoding` protocol in Objective-C.
1289
1290It is possible to use an :c:type:`NSKeyedArchiver` to store any Python object that
1291can be pickled in an Objective-C serialized data object. 
1292
1293Due to technical details it is not possible to pickle an Objective-C object,
1294unless someone explicitly implements the pickle protocol for such an object.
1295
1296Properties
1297----------
1298
1299Introduction
1300............
1301
1302Both Python and Objective-C have support for properties, which are object attributes
1303that are accessed using attribute access syntax but which result in a method call.
1304
1305The Python built-in :class:`property <__builtin__.property__` is used to define new
1306properties in plain Python code. These properties don't full interoperate with 
1307Objective-C code though because they do not necessarily implement the Objective-C
1308methods that mechanisms like Key-Value Coding use to interact with a class.
1309
1310PyObjC therefore has a number of property classes that allow you to define new
1311properties that do interact fully with the Key-Value Coding and Observation
1312frameworks.
1313
1314.. todo:: Implement method for enabling properties on existing classes and tell
1315   why that is off by default and when it will be turned on by default.
1316
1317.. todo:: The description is way to minimal, even the design document contained
1318   more information.
1319
1320.. class:: object_property(name=None, read_only=False, copy=False, dynamic=False, ivar=None, typestr=_C_ID, depends_on=None)
1321
1322
1323   :param name: Name of the property, the default is to extract the name from the class dictionary
1324   :param read_only: Is this a read-only property? The default is a read-write property.
1325   :param copy: Should the default setter method copy values? The default retains the new value without copying.
1326   :param dynamic: If this argument is :data:`True` the property will not generate default accessor, 
1327     but will rely on some external process to create them.
1328   :param ivar: Name of the instance variable that's used to store the value. When this value is :data:`None`
1329     the name will be calculated from the property name. If it is :data:`NULL` there will be no instance variable.
1330   :param typestr: The Objective-C type for this property, defaults to an arbitrary object.
1331   :param depends_on: A sequence of names of properties the value of this property depends on.
1332
1333During the class definition you can add accessor methods by using the property as a decorator
1334
1335
1336.. method:: object_property.getter
1337
1338   Decorator for defining the getter method for a property. The name of the method should be the
1339   same as the property::
1340
1341       class MyObject (NSObject):
1342
1343           prop = objc.object_property()
1344
1345           @prop.getter
1346           def prop(self):
1347              return 42
1348
1349
1350.. method:: object_property.setter
1351
1352   Decorator for defining the setter method for a property. The name of the method should be the
1353   same as the property.
1354
1355
1356.. method:: object_property.validate
1357
1358   Decorator for defining a Key-Value Coding validator for this property. 
1359
1360  
1361It is possible to override property accessor in a subclass::
1362
1363   class MySubclass (MyObject):
1364       @MyObject.prop.getter
1365       def getter(self):
1366           return "the world"
1367
1368This can also be used to convert a read-only property to a read-write one
1369by adding a setter accessor.
1370
1371
1372Properties for structured types
1373...............................
1374
1375Key-Value Coding is slightly different for structured types like sets and
1376lists (ordered and unordered collections). For this reason PyObjC also provides
1377subclasses of :class:`object_property` that are tuned for these types.
1378
1379.. class:: array_property
1380
1381   This property implements a list-like property. When you access the property
1382   you will get an object that implements the :class:`MutableSequence` ABC, and
1383   that will generate the correct Key-Value Observation notifications when
1384   the datastructure is updated.
1385
1386.. class:: set_property
1387
1388   This property implements a set-like property. When you access the property
1389   you will get an object that implements the :class:`MutableSet` ABC, and
1390   that will generate the correct Key-Value Observation notifications when
1391   the datastructure is updated.
1392
1393.. class:: dict_property
1394
1395   This property is like an :class:`object_property`, but has an empty
1396   NSMutableDictionary object as its default value. This type is mostly
1397   provided to have a complete set of property types.
1398
1399These collection properties are at this time experimental and do not yet
1400provide proper hooks for tweaking their behavior. Future versions of PyObjC
1401will provide such hooks (for example a method that will be called when an
1402item is inserted in an array property).
1403