Wrappers for the Cocoa frameworks on macOS
—
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.
Fundamental constants and types exported directly from the Foundation module for convenient access.
NSDecimal: type # Decimal number type for high-precision arithmetic
YES: bool # Objective-C boolean true (equivalent to True)
NO: bool # Objective-C boolean false (equivalent to False)
NSNotFound: int # Sentinel value indicating "not found" (0x7FFFFFFFFFFFFFFF on 64-bit)High-level Objective-C wrapper functions for internationalization and localization, providing convenient access to localized strings and attributed strings.
def NSLocalizedString(key, comment):
"""
Gets localized string for key from main bundle.
Args:
key (str): Localization key
comment (str): Developer comment for translators
Returns:
str: Localized string or key if not found
"""
def NSLocalizedStringFromTable(key, table, comment):
"""
Gets localized string from specific table in main bundle.
Args:
key (str): Localization key
table (str): Name of .strings table file
comment (str): Developer comment for translators
Returns:
str: Localized string or key if not found
"""
def NSLocalizedStringFromTableInBundle(key, table, bundle, comment):
"""
Gets localized string from table in specific bundle.
Args:
key (str): Localization key
table (str): Name of .strings table file
bundle: NSBundle containing localization resources
comment (str): Developer comment for translators
Returns:
str: Localized string or key if not found
"""
def NSLocalizedStringWithDefaultValue(key, table, bundle, value, comment):
"""
Gets localized string with explicit default value.
Args:
key (str): Localization key
table (str): Name of .strings table file
bundle: NSBundle containing localization resources
value (str): Default value if localization not found
comment (str): Developer comment for translators
Returns:
str: Localized string, default value, or key
"""
def NSLocalizedAttributedString(key, comment):
"""
Gets localized attributed string for key from main bundle.
Args:
key (str): Localization key
comment (str): Developer comment for translators
Returns:
NSAttributedString: Localized attributed string
"""
def NSLocalizedAttributedStringFromTable(key, table, comment):
"""
Gets localized attributed string from specific table.
Args:
key (str): Localization key
table (str): Name of .strings table file
comment (str): Developer comment for translators
Returns:
NSAttributedString: Localized attributed string
"""
def NSLocalizedAttributedStringFromTableInBundle(key, table, bundle, comment):
"""
Gets localized attributed string from table in bundle.
Args:
key (str): Localization key
table (str): Name of .strings table file
bundle: NSBundle containing localization resources
comment (str): Developer comment for translators
Returns:
NSAttributedString: Localized attributed string
"""
def NSLocalizedAttributedStringWithDefaultValue(key, table, bundle, value, comment):
"""
Gets localized attributed string with default value.
Args:
key (str): Localization key
table (str): Name of .strings table file
bundle: NSBundle containing localization resources
value (str): Default value if localization not found
comment (str): Developer comment for translators
Returns:
NSAttributedString: Localized attributed string or default
"""Simple mathematical utility functions commonly used in Objective-C development.
def MIN(a, b):
"""
Returns the minimum of two values.
Args:
a: First value
b: Second value
Returns:
Minimum of a and b
"""
def MAX(a, b):
"""
Returns the maximum of two values.
Args:
a: First value
b: Second value
Returns:
Maximum of a and b
"""
def ABS(x):
"""
Returns the absolute value (alias for Python's abs()).
Args:
x: Numeric value
Returns:
Absolute value of x
"""Resource management classes that provide Python context manager support for disabling macOS system behaviors during critical operations.
class NSDisabledAutomaticTermination:
"""
Context manager for temporarily disabling automatic application termination.
Usage:
with NSDisabledAutomaticTermination():
# Critical work that shouldn't be interrupted
perform_important_operation()
"""
class NSDisabledSuddenTermination:
"""
Context manager for temporarily disabling sudden application termination.
Usage:
with NSDisabledSuddenTermination():
# Critical work that needs to complete
save_user_data()
"""Safe wrapper methods for NSObject's performSelector family that handle exceptions and provide better Python integration.
# NSObject enhancements (automatically available on all NSObject instances)
def pyobjc_performSelectorOnMainThread_withObject_waitUntilDone_(sel, obj, wait):
"""
Safely executes selector on main thread with exception handling.
Args:
sel: Selector to execute
obj: Object argument to pass
wait (bool): Whether to wait for completion
Returns:
Result of selector execution or None if exception occurred
"""
def pyobjc_performSelectorOnMainThread_withObject_modes_(sel, obj, modes):
"""
Safely executes selector on main thread in specific run loop modes.
Args:
sel: Selector to execute
obj: Object argument to pass
modes: List of run loop modes
Returns:
Result of selector execution or None if exception occurred
"""
def pyobjc_performSelectorInBackground_withObject_(sel, obj):
"""
Safely executes selector in background thread.
Args:
sel: Selector to execute
obj: Object argument to pass
Returns:
None (executes asynchronously)
"""
def pyobjc_performSelector_withObject_afterDelay_(sel, obj, delay):
"""
Safely executes selector after specified delay.
Args:
sel: Selector to execute
obj: Object argument to pass
delay (float): Delay in seconds
Returns:
None (executes asynchronously)
"""Python-friendly enhancements automatically added to Foundation collection classes, providing familiar Python interfaces.
# NSAttributedString enhancements
def __len__(self):
"""Returns the length of the attributed string."""
# NSCache enhancements - dictionary-like interface
def __getitem__(self, key):
"""Gets cached object for key, raises KeyError if not found."""
def get(self, key, default=None):
"""Gets cached object for key with optional default value."""
def __setitem__(self, key, value):
"""Sets cached object for key (None values stored as NSNull)."""
def __delitem__(self, key):
"""Removes cached object for key."""
def clear(self):
"""Removes all cached objects."""
# NSHashTable enhancements - set-like interface
def __len__(self):
"""Returns number of objects in hash table."""
def __iter__(self):
"""Iterates over objects in hash table."""
def add(self, value):
"""Adds object to hash table (None stored as NSNull)."""
def remove(self, value):
"""Removes object from hash table."""
def __contains__(self, value):
"""Checks if hash table contains object."""
def pop(self):
"""Removes and returns arbitrary object from hash table."""
def clear(self):
"""Removes all objects from hash table."""
# NSIndexSet enhancements - set-like interface for indices
def __len__(self):
"""Returns count of indices in set."""
def __iter__(self):
"""Iterates over indices in ascending order."""
def __reversed__(self):
"""Iterates over indices in descending order."""
def __eq__(self, other):
"""Compares index sets for equality."""
def __ne__(self, other):
"""Compares index sets for inequality."""
def __contains__(self, value):
"""Checks if index set contains specific index."""
# NSMutableIndexSet enhancements
def clear(self):
"""Removes all indices from set."""
def add(self, value):
"""Adds index to set."""
def remove(self, value):
"""Removes index from set."""
# NSLocale enhancements - dictionary-like access
def __getitem__(self, key):
"""Gets locale information for key."""
# NSIndexPath enhancements
def __len__(self):
"""Returns length of index path."""
def __getitem__(self, index):
"""Gets index at position."""
def __add__(self, index):
"""Creates new index path with added index."""
# NSURL enhancements
def __fspath__(self):
"""Returns file system path for use with pathlib and os.path."""import Foundation
# Use Objective-C boolean constants
is_enabled = Foundation.YES
is_disabled = Foundation.NO
# Check for "not found" condition
index = some_array.indexOfObject_(target_object)
if index == Foundation.NSNotFound:
print("Object not found in array")
# Work with high-precision decimals
decimal_value = Foundation.NSDecimalNumber.decimalNumberWithString_("123.456789")import Foundation
# Basic localization
title = Foundation.NSLocalizedString("WINDOW_TITLE", "Main window title")
message = Foundation.NSLocalizedString("WELCOME_MSG", "Welcome message")
# Table-based localization
error = Foundation.NSLocalizedStringFromTable("NETWORK_ERROR", "Errors", "Network failed")
# Attributed string localization
styled_text = Foundation.NSLocalizedAttributedString("RICH_TEXT", "Styled content")import Foundation
# Prevent automatic termination during critical operations
with Foundation.NSDisabledAutomaticTermination():
save_all_documents()
perform_cleanup()
# Prevent sudden termination during user data operations
with Foundation.NSDisabledSuddenTermination():
export_user_data_to_file()import Foundation
# NSCache with dictionary-like interface
cache = Foundation.NSCache.alloc().init()
cache["user_data"] = user_object
cache["settings"] = app_settings
# Get with default
user_data = cache.get("user_data", default_user)
# Clear cache
cache.clear()
# NSIndexSet with set-like interface
index_set = Foundation.NSMutableIndexSet.indexSet()
index_set.add(5)
index_set.add(10)
index_set.add(15)
# Iterate and check membership
for index in index_set:
print(f"Index: {index}")
if 10 in index_set:
print("Contains index 10")
# NSHashTable with set-like interface
hash_table = Foundation.NSHashTable.hashTableWithOptions_(
Foundation.NSPointerFunctionsStrongMemory
)
hash_table.add("item1")
hash_table.add("item2")
# Iterate and manipulate
for item in hash_table:
print(f"Item: {item}")
hash_table.remove("item1")
hash_table.clear()import Foundation
# Create an object that responds to selectors
string_obj = Foundation.NSString.stringWithString_("Hello")
# Safely execute selector on main thread
result = string_obj.pyobjc_performSelectorOnMainThread_withObject_waitUntilDone_(
"uppercaseString",
None, # no argument needed
True # wait for completion
)
# Execute with delay
string_obj.pyobjc_performSelector_withObject_afterDelay_(
"uppercaseString",
None, # no argument
1.0 # 1 second delay
)Foundation serves as the higher-level object-oriented layer built on CoreFoundation:
import Foundation
import CoreFoundation
# Foundation objects can be used with Core Foundation functions
ns_string = Foundation.NSString.stringWithString_("Hello")
cf_string = CoreFoundation.CFSTR("World")
# They're toll-free bridged - can be used interchangeably
combined = ns_string.stringByAppendingString_(cf_string)Install with Tessl CLI
npx tessl i tessl/pypi-pyobjc-framework-cocoa