NSObject NSObject Class

Definition

Base class for all bound objects that map to Objective-C objects.

[Foundation.Register("NSObject", true)]
public class NSObject : Foundation.INSObjectProtocol, IDisposable, IEquatable<Foundation.NSObject>
type NSObject = class
    interface IEquatable<NSObject>
    interface INativeObject
    interface IDisposable
    interface INSObjectProtocol
Inheritance
NSObjectNSObject
Derived
Attributes
Implements

Remarks

This is the base class that is used to bind Objective-C classes to C# classes. Merely subclassing from NSObject will produce a class that can be passed to Objective-C.

The C# NSObject class and their subclasses are managed representations of the underlying Objective-C instances. The pointer to the unmanaged code Objective-C object is stored in the Handle property.

It is important to note that currently, the compiler does not support generic subclasses of NSObject.

Class Registration

When you create a subclass of NSObject this subclass is registered with the Objective-C runtime with a name based on the full .NET typename which is an implementation detail. If you need to ensure that a C# class is exposed with a specific name in the Objective-C runtime, you can apply the T:ObjCRuntime.RegisterAttribute to the class and specify the name that you want your class to have.

The above is typically used in cases where either you want to reference the class by name on some Objective-C code, when using Interface Builder XIB and Storyboard files or when you are using an Objective-C serialization setup (for example when using NSCoder).


//
// This exposes the C# class _MySampleView as the Objective-C MyView
//
[Export ("MyView")]
public class _MySampleView : UIView {

}

Objective-C Methods

In general, MonoTouch classes map one to one to the underlying Objective-C classes. For example, the C# class "MonoTouch.Foundation.NSObject" maps to the Objective-C "NSObject" class. But methods are different. The Objective-C methods do not translate well to C# methods, so they have been in general been altered to match both the C# language, the C# idioms and the .NET Framework Design Guidelines.

Objective-C methods are surfaced to C# as virtual methods that have the special T:ObjCRuntime.ExportAttribute applied to them. This attribute is used by the compiler to map C# names to Objective-C names. These attributes are shown in the API documentation on top of each function, to help you identify which Objective-C method a particular C# method is calling.

To alter the behavior of a class you use the standard C# idioms: create a subclass and override the methods that you want to alter and use the "base." language feature to optionally call into your base class.


public class MyView : UISlider {
    public override void Draw (RectangleF rect)
    {
        // Let the base class draw first
        base.Draw (rect);

        // Our custom code
        var ctx = UIGraphics.GetCurrentContext ();
        UIColor.Gray.SetColor ();
        ctx.StrokeEllipseInRect (rect);
    }
}

By default, only methods that have been overwritten will be exposed to the Objective-C world. If you want to expose an arbitrary C# method to the Objective-C world, you need to apply the T:ObjCRuntime.ExportAttribute to your public method. And this can be done to both static and instance methods. Once the attribute is applied, the method will be exposed to Objective-C and the standard data type marshalling operations that are supported by the runtime are made available to those methods.


//
// Exposes the class StringUtilities to Objective-C with the 
// method:
//    - (NSString *) joinArray:(NSArray *) stringArray withSeparator:(NSString *sep);
//
// Used like this:
//   id utilities = [[StringUtilities alloc] init];
//   NSLog (@"Joined: %@", [utilities joinArray:users withSeparator:@", "]);
//
public class StringUtilities : NSObject {
    [Export ("joinArray:withSeparator:")]
    public string Join (string [] array, string separator)
    {
        return string.Join (separator, array);
    }
}

Lifecycle

The C# NSObject and their subclasses are managed wrappers for the underlying Objective-C object. These are created either from C#, when you create a new instance by using the "new" operator or when an existing unmanaged object is surfaced to the C# world.

When you create an object from C# using the "new" operator, the object will initially be owned by C#, and C# will retain a reference to the object. This reference will only be dropped when the garbage collector determines that there are no pending managed references to it, or when you manually call the Dispose method on the object.

C# NSObjects are also created on demand when you invoke a method or a property that returns an NSObject. At this point, the runtime will look into an object cache and determine whether a given Objective-C NSObject has already been surfaced to the managed world or not. If the object has been surfaced, the existing object will be returned, otherwise a constructor that takes an IntPtr as a parameter is invoked to construct the object.

Pure "peers" to framework objects (those objects that are merely C# representations of an Objective-C object and have no extra managed associated state) can be recreated by the runtime on demand by using the constructor mentioned before.

User-subclasses of NSObjects often contain C# state so whenever the Objective-C runtime performs a "retain" operation on one of these objects, the runtime creates a GCHandle that keeps the managed object alive, even if there are no C# visible references to the object. This simplifies bookeeping a lot, since the state will be preserved automatically for you.

The Dispose operation on an NSObject will always drop the reference to the underlying Objective-C object, but will not destroy the managed state, this will only happen when both the managed code and the unmanaged code have both released the objects. This is slightly different from .NET, because on .NET once an object is disposed, it is not possible to invoke any methods on the object, as it is deemed to be useless. That is not the case with NSObjects.

Adopting Protocols

In MonoTouch, most Objective-C protocols are mapped to classes that have the T:ObjCRuntime.ModelAttribute applied to them. And the way that you adopt a protocol is by subclassing and overwriting the methods that you want to adopt.

There are some rare cases, where you want to adopt an ad-hoc protocol on your own. If you need to adopt an Objective-C protocol, you should use the AdoptsAttribute on your class and provide the name of the protocol that you want to adopt. Typically, when adopting a protocol, you will also have to list all of the Objective-C selectors that you are adopting using the T:ObjCRuntime.ExportAttribute.


[Adopts ("NSLocking")]
public class MyLockeingObject : NSObject {
    [Export ("lock")]
    public void Lock ()
    {
        // ...
    }

    [Export ("unlock")]
    public void Unlock ()
    {
        // ...
    }
}

Key Value Coding

Key Value coding is a mechanism that allows you to access properties of an object by their name, as opposed to accessing them directly with a C# method.

To expose a C# property to the Key-Value coding system all you need to do is add the T:ObjCRuntime.ExportAttribute to your property. The names must only contain ASCII characters, start with a lowercase letter, and must not contain any spaces.


public class CircleLayer : CALayer {
    [Export ("radius")]
    public double Radius { get; set; }

    // ...
}

You use the M:Foundation.ValueForKey(Foundation.NSString); to lookup a property using a name, and you use the of functions <xref data-throw-if-not-resolved="true" uid="Foundation.SetValueForKey(Foundation.NSObject, Foundation.NSString);"> to set the value for the specified property. For example, you could call foo.ValueForKey ("user") to grab the value of the user property in an object.

In addition, you can use Key Paths to have the runtime repeatedly call the ValueForKey or SetValueForKey for you. You separate the keys by using a dot. For example the keypath "user.address.phone.mobile" would request the user property, and then request the address property on the user, then it would request the phone property on the address and finally request the mobile property on the phone and finally use the result as the value. You use the M:Foundation.ValueForKeyPath(Foundation.NSString); to lookup a property using a keypath, and you use the <a href="https://docs.microsoft.com/en-us/search/index?search=M:Foundation.SetValueForKeyPath(Foundation.NSObject, Foundation.NSString);&scope=Xamarin" title="M:Foundation.SetValueForKeyPath(Foundation.NSObject, Foundation.NSString);">M:Foundation.SetValueForKeyPath(Foundation.NSObject, Foundation.NSString); to set a value using a keypath.

When using keypaths, if a lookup fails, the SetValueForUndefinedKey(NSObject, NSString) will be invoked when setting a value, and the ValueForUndefinedKey(NSString) will be invoked when looking up a value. Both methods by default raise an Objective-C exception, you can alter that behavior by overriding the methods.

Key Value Observing

Key value observing is a mechanism implemented by NSObject that can be used to monitor changes being done to an NSObject through the Key Value Coding system.

For your class to observe a notification, you must override the ObserveValue(NSString, NSObject, NSDictionary, IntPtr) method which will be invoked with the information about the value changes for a specific keypath. Then you use the AddObserver(NSObject, NSString, NSKeyValueObservingOptions, IntPtr) to start observing changes and the RemoveObserver(NSObject, NSString, IntPtr) method to stop receiving notifications.

Constructors

NSObject() NSObject()

Default constructor that initializes a new instance of this class with no parameters.

NSObject(NSObjectFlag) NSObject(NSObjectFlag)

Constructor to call on derived classes to skip initialization and merely allocate the object.

NSObject(IntPtr) NSObject(IntPtr)

A constructor used when creating managed representations of unmanaged objects; Called by the runtime.

NSObject(IntPtr, Boolean) NSObject(IntPtr, Boolean)

A constructor used when creating managed representations of unmanaged objects; Called by the runtime.

Fields

MonoTouchAssembly MonoTouchAssembly

Points to the montoouch assembly.

PlatformAssembly PlatformAssembly

Properties

ChangeIndexesKey ChangeIndexesKey

Represents the value associated with the constant NSKeyValueChangeIndexesKey

ChangeKindKey ChangeKindKey

Represents the value associated with the constant NSKeyValueChangeKindKey

ChangeNewKey ChangeNewKey

Represents the value associated with the constant NSKeyValueChangeNewKey

ChangeNotificationIsPriorKey ChangeNotificationIsPriorKey

Notification constant for ChangeNotificati

ChangeOldKey ChangeOldKey

Represents the value associated with the constant NSKeyValueChangeOldKey

Class Class
ClassHandle ClassHandle

The handle for this class.

DebugDescription DebugDescription

A developer-meaningful description of this object.

Description Description

Description of the object, the Objective-C version of ToString.

Handle Handle

Handle (pointer) to the unmanaged object representation.

IsDirectBinding IsDirectBinding
IsProxy IsProxy
RetainCount RetainCount

Returns the current Objective-C retain count for the object.

Self Self
Superclass Superclass
SuperHandle SuperHandle

Handle used to represent the methods in the base class for this NSObject.

Zone Zone

Methods

AddObserver(NSString, NSKeyValueObservingOptions, Action<NSObservedChange>) AddObserver(NSString, NSKeyValueObservingOptions, Action<NSObservedChange>)

Registers an object for being observed externally using an arbitrary method.

AddObserver(String, NSKeyValueObservingOptions, Action<NSObservedChange>) AddObserver(String, NSKeyValueObservingOptions, Action<NSObservedChange>)

Registers an object for being observed externally using an arbitrary method.

AddObserver(NSObject, NSString, NSKeyValueObservingOptions, IntPtr) AddObserver(NSObject, NSString, NSKeyValueObservingOptions, IntPtr)

Registers an object for being observed externally (using NSString keyPath). Observed changes are dispatched to the observer’s object ObserveValue(NSString, NSObject, NSDictionary, IntPtr) method.

AddObserver(NSObject, String, NSKeyValueObservingOptions, IntPtr) AddObserver(NSObject, String, NSKeyValueObservingOptions, IntPtr)

Registers an object for being observed externally (using string keyPath). Observed changes are dispatched to the observer’s object ObserveValue(NSString, NSObject, NSDictionary, IntPtr) method.

Alloc(Class) Alloc(Class)
AutomaticallyNotifiesObserversForKey(String) AutomaticallyNotifiesObserversForKey(String)

Whether this object is providing key-value notifications for the specified key.

AwakeFromNib() AwakeFromNib()

Called after the object has been loaded from the nib file. Overriders must call base.AwakeFromNib().

BeginInvokeOnMainThread(Selector, NSObject) BeginInvokeOnMainThread(Selector, NSObject)

Invokes asynchrously the specified code on the main UI thread.

BeginInvokeOnMainThread(Action) BeginInvokeOnMainThread(Action)
CancelPreviousPerformRequest(NSObject) CancelPreviousPerformRequest(NSObject)

Cancels a pending time-delayed Invoke or PerformSelector.

CancelPreviousPerformRequest(NSObject, Selector, NSObject) CancelPreviousPerformRequest(NSObject, Selector, NSObject)

Cancels a pending time-delayed PerformSelector.

ConformsToProtocol(IntPtr) ConformsToProtocol(IntPtr)

Invoked to determine if this object implements the specified protocol.

Copy() Copy()

Performs a copy of the underlying Objective-C object.

DangerousAutorelease() DangerousAutorelease()
DangerousRelease() DangerousRelease()
DangerousRetain() DangerousRetain()
DidChange(NSKeyValueChange, NSIndexSet, NSString) DidChange(NSKeyValueChange, NSIndexSet, NSString)

Indicates a change occurred to the indexes for a to-many relationship.

DidChange(NSString, NSKeyValueSetMutationKind, NSSet) DidChange(NSString, NSKeyValueSetMutationKind, NSSet)
DidChangeValue(String) DidChangeValue(String)

Indicates that a change occurred on the specified key.

Dispose() Dispose()

Releases the resources used by the NSObject object.

Dispose(Boolean) Dispose(Boolean)

Releases the resources used by the NSObject object.

DoesNotRecognizeSelector(Selector) DoesNotRecognizeSelector(Selector)

Indicates that this object does not recognize the specified selector.

Equals(Object) Equals(Object)
Equals(NSObject) Equals(NSObject)
Finalize() Finalize()

Finalizer for the NSObject object

FromObject(Object) FromObject(Object)

Boxes an object into an NSObject.

GetDictionaryOfValuesFromKeys(NSString[]) GetDictionaryOfValuesFromKeys(NSString[])

Retrieves the values of the specified keys.

GetHashCode() GetHashCode()

Generates a hash code for the current instance.

GetKeyPathsForValuesAffecting(NSString) GetKeyPathsForValuesAffecting(NSString)

The key paths whose values affect the value of the specified key.

GetMethodForSelector(Selector) GetMethodForSelector(Selector)
GetNativeField(String) GetNativeField(String)
GetNativeHash() GetNativeHash()
Init() Init()
InitializeHandle(IntPtr, String) InitializeHandle(IntPtr, String)
InitializeHandle(IntPtr) InitializeHandle(IntPtr)
Invoke(Action, Double) Invoke(Action, Double)
Invoke(Action, TimeSpan) Invoke(Action, TimeSpan)
InvokeInBackground(Action) InvokeInBackground(Action)
InvokeOnMainThread(Action) InvokeOnMainThread(Action)
InvokeOnMainThread(Selector, NSObject) InvokeOnMainThread(Selector, NSObject)

Invokes synchrously the specified code on the main UI thread.

IsEqual(NSObject) IsEqual(NSObject)
IsKindOfClass(Class) IsKindOfClass(Class)
IsMemberOfClass(Class) IsMemberOfClass(Class)
IsNewRefcountEnabled() IsNewRefcountEnabled()

Internal -- Determines whether MonoTouch is using the new toggle-reference system or not

MarkDirty() MarkDirty()

Promotes a regular peer object (IsDirectBinding is true) into a toggleref object.

MutableCopy() MutableCopy()

Creates a mutable copy of the specified NSObject.

ObserveValue(NSString, NSObject, NSDictionary, IntPtr) ObserveValue(NSString, NSObject, NSDictionary, IntPtr)

Indicates that the value at the specified keyPath relative to this object has changed.

PerformSelector(Selector) PerformSelector(Selector)
PerformSelector(Selector, NSObject) PerformSelector(Selector, NSObject)
PerformSelector(Selector, NSObject, NSObject) PerformSelector(Selector, NSObject, NSObject)
PerformSelector(Selector, NSObject, Double) PerformSelector(Selector, NSObject, Double)

Invokes the selector on the current instance and if the obj is not null, it passes this as its single parameter.

PerformSelector(Selector, NSObject, Double, NSString[]) PerformSelector(Selector, NSObject, Double, NSString[])
PerformSelector(Selector, NSThread, NSObject, Boolean) PerformSelector(Selector, NSThread, NSObject, Boolean)
PerformSelector(Selector, NSThread, NSObject, Boolean, NSString[]) PerformSelector(Selector, NSThread, NSObject, Boolean, NSString[])
PrepareForInterfaceBuilder() PrepareForInterfaceBuilder()
RemoveObserver(NSObject, NSString) RemoveObserver(NSObject, NSString)

Stops the specified observer from receiving further notifications of changed values for the specified keyPath.

RemoveObserver(NSObject, String) RemoveObserver(NSObject, String)

Stops the specified observer from receiving further notifications of changed values for the specified keyPath.

RemoveObserver(NSObject, NSString, IntPtr) RemoveObserver(NSObject, NSString, IntPtr)

Stops the specified observer from receiving further notifications of changed values for the specified keyPath and context.

RemoveObserver(NSObject, String, IntPtr) RemoveObserver(NSObject, String, IntPtr)

Stops the specified observer from receiving further notifications of changed values for the specified keyPath and context.

RespondsToSelector(Selector) RespondsToSelector(Selector)

Whether this object recognizes the specified selector.

SetNativeField(String, NSObject) SetNativeField(String, NSObject)
SetNilValueForKey(NSString) SetNilValueForKey(NSString)

Sets the value of the specified key to null.

SetValueForKey(NSObject, NSString) SetValueForKey(NSObject, NSString)

Sets the value of the property specified by the key to the specified value.

SetValueForKeyPath(IntPtr, NSString) SetValueForKeyPath(IntPtr, NSString)

A constructor used when creating managed representations of unmanaged objects; Called by the runtime.

SetValueForKeyPath(NSObject, NSString) SetValueForKeyPath(NSObject, NSString)

Sets the value of a property that can be reached using a keypath.

SetValueForUndefinedKey(NSObject, NSString) SetValueForUndefinedKey(NSObject, NSString)

Indicates an attempt to write a value to an undefined key. If not overridden, raises an NSUndefinedKeyException.

SetValuesForKeysWithDictionary(NSDictionary) SetValuesForKeysWithDictionary(NSDictionary)

Sets the values of this NSObject to those in the specified dictionary.

ToString() ToString()

Returns a string representation of the value of the current instance.

ValueForKey(NSString) ValueForKey(NSString)

Returns the value of the property associated with the specified key.

ValueForKeyPath(NSString) ValueForKeyPath(NSString)

Returns the value of a property that can be reached using a keypath.

ValueForUndefinedKey(NSString) ValueForUndefinedKey(NSString)

Indicates an attempt to read a value of an undefined key. If not overridden, raises an NSUndefinedKeyException.

WillChange(NSKeyValueChange, NSIndexSet, NSString) WillChange(NSKeyValueChange, NSIndexSet, NSString)

Indicates that the values of the specified indices in the specified key are about to change.

WillChange(NSString, NSKeyValueSetMutationKind, NSSet) WillChange(NSString, NSKeyValueSetMutationKind, NSSet)
WillChangeValue(String) WillChangeValue(String)

Indicates that the value of the specified key is about to change.

Extension Methods

GetDebugDescription(INSObjectProtocol) GetDebugDescription(INSObjectProtocol)
GetAccessibilityCustomRotors(NSObject) GetAccessibilityCustomRotors(NSObject)

Gets the array of UIAccessibilityCustomRotor objects appropriate for this object.

SetAccessibilityCustomRotors(NSObject, UIAccessibilityCustomRotor[]) SetAccessibilityCustomRotors(NSObject, UIAccessibilityCustomRotor[])

Sets the array of UIAccessibilityCustomRotor objects appropriate for this object.

Applies to

See also