0
# Foundation Framework
1
2
High-level Objective-C framework providing object-oriented wrappers around Core Foundation APIs. Foundation includes essential classes for strings, collections, dates, URLs, and system services that form the backbone of macOS and iOS development.
3
4
## Capabilities
5
6
### Special Constants and Types
7
8
Fundamental constants and types exported directly from the Foundation module for convenient access.
9
10
```python { .api }
11
NSDecimal: type # Decimal number type for high-precision arithmetic
12
YES: bool # Objective-C boolean true (equivalent to True)
13
NO: bool # Objective-C boolean false (equivalent to False)
14
NSNotFound: int # Sentinel value indicating "not found" (0x7FFFFFFFFFFFFFFF on 64-bit)
15
```
16
17
### Localization Functions
18
19
High-level Objective-C wrapper functions for internationalization and localization, providing convenient access to localized strings and attributed strings.
20
21
```python { .api }
22
def NSLocalizedString(key, comment):
23
"""
24
Gets localized string for key from main bundle.
25
26
Args:
27
key (str): Localization key
28
comment (str): Developer comment for translators
29
30
Returns:
31
str: Localized string or key if not found
32
"""
33
34
def NSLocalizedStringFromTable(key, table, comment):
35
"""
36
Gets localized string from specific table in main bundle.
37
38
Args:
39
key (str): Localization key
40
table (str): Name of .strings table file
41
comment (str): Developer comment for translators
42
43
Returns:
44
str: Localized string or key if not found
45
"""
46
47
def NSLocalizedStringFromTableInBundle(key, table, bundle, comment):
48
"""
49
Gets localized string from table in specific bundle.
50
51
Args:
52
key (str): Localization key
53
table (str): Name of .strings table file
54
bundle: NSBundle containing localization resources
55
comment (str): Developer comment for translators
56
57
Returns:
58
str: Localized string or key if not found
59
"""
60
61
def NSLocalizedStringWithDefaultValue(key, table, bundle, value, comment):
62
"""
63
Gets localized string with explicit default value.
64
65
Args:
66
key (str): Localization key
67
table (str): Name of .strings table file
68
bundle: NSBundle containing localization resources
69
value (str): Default value if localization not found
70
comment (str): Developer comment for translators
71
72
Returns:
73
str: Localized string, default value, or key
74
"""
75
76
def NSLocalizedAttributedString(key, comment):
77
"""
78
Gets localized attributed string for key from main bundle.
79
80
Args:
81
key (str): Localization key
82
comment (str): Developer comment for translators
83
84
Returns:
85
NSAttributedString: Localized attributed string
86
"""
87
88
def NSLocalizedAttributedStringFromTable(key, table, comment):
89
"""
90
Gets localized attributed string from specific table.
91
92
Args:
93
key (str): Localization key
94
table (str): Name of .strings table file
95
comment (str): Developer comment for translators
96
97
Returns:
98
NSAttributedString: Localized attributed string
99
"""
100
101
def NSLocalizedAttributedStringFromTableInBundle(key, table, bundle, comment):
102
"""
103
Gets localized attributed string from table in bundle.
104
105
Args:
106
key (str): Localization key
107
table (str): Name of .strings table file
108
bundle: NSBundle containing localization resources
109
comment (str): Developer comment for translators
110
111
Returns:
112
NSAttributedString: Localized attributed string
113
"""
114
115
def NSLocalizedAttributedStringWithDefaultValue(key, table, bundle, value, comment):
116
"""
117
Gets localized attributed string with default value.
118
119
Args:
120
key (str): Localization key
121
table (str): Name of .strings table file
122
bundle: NSBundle containing localization resources
123
value (str): Default value if localization not found
124
comment (str): Developer comment for translators
125
126
Returns:
127
NSAttributedString: Localized attributed string or default
128
"""
129
```
130
131
### Mathematical Utility Functions
132
133
Simple mathematical utility functions commonly used in Objective-C development.
134
135
```python { .api }
136
def MIN(a, b):
137
"""
138
Returns the minimum of two values.
139
140
Args:
141
a: First value
142
b: Second value
143
144
Returns:
145
Minimum of a and b
146
"""
147
148
def MAX(a, b):
149
"""
150
Returns the maximum of two values.
151
152
Args:
153
a: First value
154
b: Second value
155
156
Returns:
157
Maximum of a and b
158
"""
159
160
def ABS(x):
161
"""
162
Returns the absolute value (alias for Python's abs()).
163
164
Args:
165
x: Numeric value
166
167
Returns:
168
Absolute value of x
169
"""
170
```
171
172
### Context Manager Classes
173
174
Resource management classes that provide Python context manager support for disabling macOS system behaviors during critical operations.
175
176
```python { .api }
177
class NSDisabledAutomaticTermination:
178
"""
179
Context manager for temporarily disabling automatic application termination.
180
181
Usage:
182
with NSDisabledAutomaticTermination():
183
# Critical work that shouldn't be interrupted
184
perform_important_operation()
185
"""
186
187
class NSDisabledSuddenTermination:
188
"""
189
Context manager for temporarily disabling sudden application termination.
190
191
Usage:
192
with NSDisabledSuddenTermination():
193
# Critical work that needs to complete
194
save_user_data()
195
"""
196
```
197
198
### Enhanced NSObject Methods
199
200
Safe wrapper methods for NSObject's performSelector family that handle exceptions and provide better Python integration.
201
202
```python { .api }
203
# NSObject enhancements (automatically available on all NSObject instances)
204
def pyobjc_performSelectorOnMainThread_withObject_waitUntilDone_(sel, obj, wait):
205
"""
206
Safely executes selector on main thread with exception handling.
207
208
Args:
209
sel: Selector to execute
210
obj: Object argument to pass
211
wait (bool): Whether to wait for completion
212
213
Returns:
214
Result of selector execution or None if exception occurred
215
"""
216
217
def pyobjc_performSelectorOnMainThread_withObject_modes_(sel, obj, modes):
218
"""
219
Safely executes selector on main thread in specific run loop modes.
220
221
Args:
222
sel: Selector to execute
223
obj: Object argument to pass
224
modes: List of run loop modes
225
226
Returns:
227
Result of selector execution or None if exception occurred
228
"""
229
230
def pyobjc_performSelectorInBackground_withObject_(sel, obj):
231
"""
232
Safely executes selector in background thread.
233
234
Args:
235
sel: Selector to execute
236
obj: Object argument to pass
237
238
Returns:
239
None (executes asynchronously)
240
"""
241
242
def pyobjc_performSelector_withObject_afterDelay_(sel, obj, delay):
243
"""
244
Safely executes selector after specified delay.
245
246
Args:
247
sel: Selector to execute
248
obj: Object argument to pass
249
delay (float): Delay in seconds
250
251
Returns:
252
None (executes asynchronously)
253
"""
254
```
255
256
### Enhanced Collection Classes
257
258
Python-friendly enhancements automatically added to Foundation collection classes, providing familiar Python interfaces.
259
260
```python { .api }
261
# NSAttributedString enhancements
262
def __len__(self):
263
"""Returns the length of the attributed string."""
264
265
# NSCache enhancements - dictionary-like interface
266
def __getitem__(self, key):
267
"""Gets cached object for key, raises KeyError if not found."""
268
269
def get(self, key, default=None):
270
"""Gets cached object for key with optional default value."""
271
272
def __setitem__(self, key, value):
273
"""Sets cached object for key (None values stored as NSNull)."""
274
275
def __delitem__(self, key):
276
"""Removes cached object for key."""
277
278
def clear(self):
279
"""Removes all cached objects."""
280
281
# NSHashTable enhancements - set-like interface
282
def __len__(self):
283
"""Returns number of objects in hash table."""
284
285
def __iter__(self):
286
"""Iterates over objects in hash table."""
287
288
def add(self, value):
289
"""Adds object to hash table (None stored as NSNull)."""
290
291
def remove(self, value):
292
"""Removes object from hash table."""
293
294
def __contains__(self, value):
295
"""Checks if hash table contains object."""
296
297
def pop(self):
298
"""Removes and returns arbitrary object from hash table."""
299
300
def clear(self):
301
"""Removes all objects from hash table."""
302
303
# NSIndexSet enhancements - set-like interface for indices
304
def __len__(self):
305
"""Returns count of indices in set."""
306
307
def __iter__(self):
308
"""Iterates over indices in ascending order."""
309
310
def __reversed__(self):
311
"""Iterates over indices in descending order."""
312
313
def __eq__(self, other):
314
"""Compares index sets for equality."""
315
316
def __ne__(self, other):
317
"""Compares index sets for inequality."""
318
319
def __contains__(self, value):
320
"""Checks if index set contains specific index."""
321
322
# NSMutableIndexSet enhancements
323
def clear(self):
324
"""Removes all indices from set."""
325
326
def add(self, value):
327
"""Adds index to set."""
328
329
def remove(self, value):
330
"""Removes index from set."""
331
332
# NSLocale enhancements - dictionary-like access
333
def __getitem__(self, key):
334
"""Gets locale information for key."""
335
336
# NSIndexPath enhancements
337
def __len__(self):
338
"""Returns length of index path."""
339
340
def __getitem__(self, index):
341
"""Gets index at position."""
342
343
def __add__(self, index):
344
"""Creates new index path with added index."""
345
346
# NSURL enhancements
347
def __fspath__(self):
348
"""Returns file system path for use with pathlib and os.path."""
349
```
350
351
## Usage Examples
352
353
### Working with Constants
354
355
```python
356
import Foundation
357
358
# Use Objective-C boolean constants
359
is_enabled = Foundation.YES
360
is_disabled = Foundation.NO
361
362
# Check for "not found" condition
363
index = some_array.indexOfObject_(target_object)
364
if index == Foundation.NSNotFound:
365
print("Object not found in array")
366
367
# Work with high-precision decimals
368
decimal_value = Foundation.NSDecimalNumber.decimalNumberWithString_("123.456789")
369
```
370
371
### Localization
372
373
```python
374
import Foundation
375
376
# Basic localization
377
title = Foundation.NSLocalizedString("WINDOW_TITLE", "Main window title")
378
message = Foundation.NSLocalizedString("WELCOME_MSG", "Welcome message")
379
380
# Table-based localization
381
error = Foundation.NSLocalizedStringFromTable("NETWORK_ERROR", "Errors", "Network failed")
382
383
# Attributed string localization
384
styled_text = Foundation.NSLocalizedAttributedString("RICH_TEXT", "Styled content")
385
```
386
387
### Context Managers
388
389
```python
390
import Foundation
391
392
# Prevent automatic termination during critical operations
393
with Foundation.NSDisabledAutomaticTermination():
394
save_all_documents()
395
perform_cleanup()
396
397
# Prevent sudden termination during user data operations
398
with Foundation.NSDisabledSuddenTermination():
399
export_user_data_to_file()
400
```
401
402
### Enhanced Collection Usage
403
404
```python
405
import Foundation
406
407
# NSCache with dictionary-like interface
408
cache = Foundation.NSCache.alloc().init()
409
cache["user_data"] = user_object
410
cache["settings"] = app_settings
411
412
# Get with default
413
user_data = cache.get("user_data", default_user)
414
415
# Clear cache
416
cache.clear()
417
418
# NSIndexSet with set-like interface
419
index_set = Foundation.NSMutableIndexSet.indexSet()
420
index_set.add(5)
421
index_set.add(10)
422
index_set.add(15)
423
424
# Iterate and check membership
425
for index in index_set:
426
print(f"Index: {index}")
427
428
if 10 in index_set:
429
print("Contains index 10")
430
431
# NSHashTable with set-like interface
432
hash_table = Foundation.NSHashTable.hashTableWithOptions_(
433
Foundation.NSPointerFunctionsStrongMemory
434
)
435
hash_table.add("item1")
436
hash_table.add("item2")
437
438
# Iterate and manipulate
439
for item in hash_table:
440
print(f"Item: {item}")
441
442
hash_table.remove("item1")
443
hash_table.clear()
444
```
445
446
### Safe Selector Execution
447
448
```python
449
import Foundation
450
451
# Create an object that responds to selectors
452
string_obj = Foundation.NSString.stringWithString_("Hello")
453
454
# Safely execute selector on main thread
455
result = string_obj.pyobjc_performSelectorOnMainThread_withObject_waitUntilDone_(
456
"uppercaseString",
457
None, # no argument needed
458
True # wait for completion
459
)
460
461
# Execute with delay
462
string_obj.pyobjc_performSelector_withObject_afterDelay_(
463
"uppercaseString",
464
None, # no argument
465
1.0 # 1 second delay
466
)
467
```
468
469
## Framework Integration
470
471
Foundation serves as the higher-level object-oriented layer built on CoreFoundation:
472
473
```python
474
import Foundation
475
import CoreFoundation
476
477
# Foundation objects can be used with Core Foundation functions
478
ns_string = Foundation.NSString.stringWithString_("Hello")
479
cf_string = CoreFoundation.CFSTR("World")
480
481
# They're toll-free bridged - can be used interchangeably
482
combined = ns_string.stringByAppendingString_(cf_string)
483
```