0
# Method and Class Decorators
1
2
Decorators and utilities for creating Objective-C methods, defining method signatures, creating categories, and handling protocol conformance. These tools are essential for creating Python classes that integrate seamlessly with Objective-C.
3
4
## Capabilities
5
6
### Method Signature Decorators
7
8
Decorators for defining and managing Objective-C method signatures and type information.
9
10
```python { .api }
11
def signature(signature: str):
12
"""
13
Decorator to set the Objective-C type signature for a method.
14
15
Args:
16
signature (str): Objective-C type encoding string
17
18
Usage:
19
@objc.signature(b'v@:i')
20
def setIntValue_(self, value):
21
self._value = value
22
"""
23
24
def callbackFor(signature: str):
25
"""
26
Decorator to mark a function as a callback with a specific signature.
27
28
Args:
29
signature (str): Objective-C type encoding for the callback
30
31
Usage:
32
@objc.callbackFor(b'v@:@')
33
def completion_handler(result):
34
print(f"Completed with: {result}")
35
"""
36
37
def selectorFor(signature: str):
38
"""
39
Decorator to create a selector from a signature.
40
41
Args:
42
signature (str): Method signature to create selector for
43
"""
44
45
def typedSelector(signature: str):
46
"""
47
Decorator to create a typed selector with explicit signature.
48
49
Args:
50
signature (str): Complete type signature for the selector
51
"""
52
53
def namedSelector(name: str, signature: str = None):
54
"""
55
Decorator to create a selector with a specific name and optional signature.
56
57
Args:
58
name (str): The selector name to use
59
signature (str, optional): Type signature for the selector
60
61
Usage:
62
@objc.namedSelector("performAction:withObject:", signature="v@:@@")
63
def doSomething_withThing_(self, action, thing):
64
pass
65
"""
66
67
def accessor(func, typeSignature: str):
68
"""
69
Decorator to create a property accessor with type signature.
70
71
Args:
72
func: The accessor function
73
typeSignature (str): Objective-C type encoding
74
75
Usage:
76
@objc.accessor
77
def getTitle(self):
78
return self._title
79
"""
80
81
def typedAccessor(typeSignature: str):
82
"""
83
Decorator to create a typed property accessor.
84
85
Args:
86
typeSignature (str): Objective-C type encoding
87
88
Usage:
89
@objc.typedAccessor("@")
90
def title(self):
91
return self._title
92
"""
93
94
def callbackPointer(closure):
95
"""
96
Create a callback pointer from a closure.
97
98
Args:
99
closure: The closure to convert to a pointer
100
101
Returns:
102
Callback pointer suitable for C function calls
103
104
Usage:
105
def my_callback(value):
106
print(f"Callback: {value}")
107
108
ptr = objc.callbackPointer(my_callback)
109
"""
110
```
111
112
### Method Type Decorators
113
114
Decorators for marking methods as class methods or instance methods in the Objective-C sense.
115
116
```python { .api }
117
def classmethod(func):
118
"""
119
Use Python's built-in classmethod decorator for Objective-C class methods.
120
121
Args:
122
func: The method to mark as a class method
123
124
Note: PyObjC uses Python's built-in classmethod decorator, not objc.classmethod
125
126
Usage:
127
@classmethod
128
def sharedInstance(cls):
129
return cls.alloc().init()
130
"""
131
132
def instancemethod(func):
133
"""
134
Decorator to mark a method as an Objective-C instance method.
135
136
Args:
137
func: The method to mark as an instance method
138
139
Usage:
140
@objc.instancemethod
141
def doSomething(self):
142
pass
143
"""
144
```
145
146
### Category Support
147
148
Decorators and functions for adding methods to existing Objective-C classes via categories.
149
150
```python { .api }
151
def category(baseClass):
152
"""
153
Decorator to add category methods to an existing Objective-C class.
154
155
Args:
156
baseClass: The Objective-C class to extend
157
158
Usage:
159
@objc.category(NSString)
160
class NSStringExtensions:
161
def isPythonic(self):
162
return self.hasPrefix_("py")
163
"""
164
165
def synthesize(name: str, copy: bool = False, readwrite: bool = True, type: str = None, ivar: str = None):
166
"""
167
Decorator to synthesize property accessors.
168
169
Args:
170
name (str): Property name to synthesize
171
copy (bool): Whether to use copy semantics
172
readwrite (bool): Whether the property is read-write
173
type (str): Type encoding for the property
174
ivar (str): Instance variable name
175
176
Usage:
177
@objc.synthesize('title', copy=True)
178
@objc.synthesize('count', type='i')
179
class MyClass(NSObject):
180
pass
181
"""
182
```
183
184
### Interface Builder Support
185
186
Decorators for Interface Builder integration and designable views.
187
188
```python { .api }
189
def IBOutlet(name: str = None):
190
"""
191
Create an Interface Builder outlet property.
192
193
Args:
194
name (str, optional): Name for the outlet
195
196
Usage:
197
myButton = objc.IBOutlet()
198
customLabel = objc.IBOutlet("titleLabel")
199
"""
200
201
def IBAction(func):
202
"""
203
Decorator to mark a method as an Interface Builder action.
204
205
Args:
206
func: The method to mark as an IBAction
207
208
Usage:
209
@objc.IBAction
210
def buttonClicked_(self, sender):
211
print("Button was clicked!")
212
"""
213
214
def IBInspectable(func):
215
"""
216
Decorator to mark a property as inspectable in Interface Builder.
217
218
Args:
219
func: The property method to mark as inspectable
220
221
Usage:
222
@objc.IBInspectable
223
def cornerRadius(self):
224
return self._cornerRadius
225
"""
226
227
def IB_DESIGNABLE(cls):
228
"""
229
Decorator to mark a class as designable in Interface Builder.
230
231
Args:
232
cls: The class to mark as designable
233
234
Usage:
235
@objc.IB_DESIGNABLE
236
class MyCustomView(NSView):
237
pass
238
"""
239
```
240
241
### Property System
242
243
Property descriptor classes for different data types and behaviors.
244
245
```python { .api }
246
def object_property(name: str = None, ivar: str = None, copy: bool = False, **kwargs):
247
"""
248
Create an object property descriptor.
249
250
Args:
251
name (str): Property name
252
ivar (str): Instance variable name
253
copy (bool): Use copy semantics
254
**kwargs: Additional property attributes
255
256
Usage:
257
title = objc.object_property(copy=True)
258
"""
259
260
def bool_property(name: str = None, ivar: str = None, **kwargs):
261
"""
262
Create a boolean property descriptor.
263
264
Args:
265
name (str): Property name
266
ivar (str): Instance variable name
267
**kwargs: Additional property attributes
268
269
Usage:
270
isEnabled = objc.bool_property()
271
"""
272
273
def array_property(name: str = None, ivar: str = None, copy: bool = False, **kwargs):
274
"""
275
Create an array property descriptor.
276
277
Args:
278
name (str): Property name
279
ivar (str): Instance variable name
280
copy (bool): Use copy semantics
281
**kwargs: Additional property attributes
282
283
Usage:
284
items = objc.array_property(copy=True)
285
"""
286
287
def set_property(name: str = None, ivar: str = None, copy: bool = False, **kwargs):
288
"""
289
Create a set property descriptor.
290
291
Args:
292
name (str): Property name
293
ivar (str): Instance variable name
294
copy (bool): Use copy semantics
295
**kwargs: Additional property attributes
296
297
Usage:
298
tags = objc.set_property(copy=True)
299
"""
300
301
def dict_property(name: str = None, ivar: str = None, copy: bool = False, **kwargs):
302
"""
303
Create a dictionary property descriptor.
304
305
Args:
306
name (str): Property name
307
ivar (str): Instance variable name
308
copy (bool): Use copy semantics
309
**kwargs: Additional property attributes
310
311
Usage:
312
metadata = objc.dict_property(copy=True)
313
"""
314
```
315
316
### Advanced Decorators
317
318
Advanced decorators for specialized method handling and closure support.
319
320
```python { .api }
321
class Accessor:
322
"""
323
Generic accessor descriptor for Objective-C properties.
324
325
Provides flexible property access patterns with automatic
326
getter/setter generation and type conversion.
327
"""
328
329
class ivar:
330
"""
331
Instance variable descriptor for Objective-C classes.
332
333
Provides direct access to Objective-C instance variables from Python
334
with proper type conversion and memory management.
335
"""
336
337
def _makeClosure(callable, signature: str):
338
"""
339
Create a closure for callback functions.
340
341
Args:
342
callable: The Python function to wrap
343
signature (str): Objective-C type signature
344
345
Returns:
346
Closure object suitable for callback usage
347
"""
348
349
def _closurePointer(closure):
350
"""
351
Get the pointer for a closure object.
352
353
Args:
354
closure: The closure object
355
356
Returns:
357
Pointer to the closure implementation
358
"""
359
```
360
361
### Context and Availability Decorators
362
363
Decorators for version checking and context management.
364
365
```python { .api }
366
def macos_available(major: int, minor: int = 0, patch: int = 0):
367
"""
368
Decorator to check macOS version availability.
369
370
Args:
371
major (int): Major version number
372
minor (int): Minor version number (default: 0)
373
patch (int): Patch version number (default: 0)
374
375
Usage:
376
@objc.macos_available(10, 15)
377
def useNewAPI(self):
378
# Only available on macOS 10.15+
379
pass
380
"""
381
382
def os_available(*args):
383
"""
384
Decorator to check OS availability across platforms.
385
386
Args:
387
*args: Version requirements for different platforms
388
"""
389
```
390
391
## Usage Examples
392
393
### Creating an Objective-C Class in Python
394
395
```python
396
import objc
397
from Foundation import NSObject
398
399
class MyCustomClass(NSObject):
400
401
@objc.synthesize('title')
402
@objc.synthesize('count')
403
404
def init(self):
405
self = objc.super(MyCustomClass, self).init()
406
if self is None:
407
return None
408
self.setTitle_("Default Title")
409
self.setCount_(0)
410
return self
411
412
@objc.signature(b'v@:i')
413
def incrementCountBy_(self, amount):
414
self.setCount_(self.count() + amount)
415
416
@objc.classmethod
417
def sharedInstance(cls):
418
if not hasattr(cls, '_shared'):
419
cls._shared = cls.alloc().init()
420
return cls._shared
421
```
422
423
### Adding a Category to NSString
424
425
```python
426
import objc
427
from Foundation import NSString
428
429
@objc.category(NSString)
430
class NSStringPythonExtensions:
431
432
def isPythonic(self):
433
return self.hasPrefix_("py") or self.hasSuffix_(".py")
434
435
@objc.signature(b'@@:@')
436
def stringByAppendingPythonSuffix_(self, suffix):
437
return self.stringByAppendingFormat_("_py_%@", suffix)
438
```