NSObject Class Reference

Inherits from
none (NSObject is a root class)
Conforms to
Framework
/System/Library/Frameworks/Foundation.framework
Availability
Available in iOS 2.0 and later.
Declared in
NSKeyedArchiver.h
NSObject.h
NSRunLoop.h
NSThread.h
objc/NSObject.h
Related sample code

Overview

NSObject is the root class of most Objective-C class hierarchies. Through NSObject, objects inherit a basic interface to the runtime system and the ability to behave as Objective-C objects.

Tasks

Initializing a Class

Creating, Copying, and Deallocating Objects

Identifying Classes

Testing Class Functionality

Testing Protocol Conformance

Obtaining Information About Methods

Describing Objects

Discardable Content Proxy Support

Sending Messages

Forwarding Messages

Dynamically Resolving Methods

Error Handling

Archiving

Deprecated Methods

Class Methods

alloc

Returns a new instance of the receiving class.

+ (id)alloc
Return Value

A new instance of the receiver.

Discussion

The isa instance variable of the new instance is initialized to a data structure that describes the class; memory for all other instance variables is set to 0.

You must use an init... method to complete the initialization process. For example:

TheClass *newObject = [[TheClass alloc] init];

Do not override alloc to include initialization code. Instead, implement class-specific versions of init... methods.

For historical reasons, alloc invokes allocWithZone:.

Availability
  • Available in iOS 2.0 and later.
See Also
Declared In
objc/NSObject.h

allocWithZone:

Returns a new instance of the receiving class.

+ (id)allocWithZone:(NSZone *)zone
Parameters
zone

This parameter is ignored.

Return Value

A new instance of the receiver.

Discussion

The isa instance variable of the new instance is initialized to a data structure that describes the class; memory for all other instance variables is set to 0.

You must use an init... method to complete the initialization process. For example:

TheClass *newObject = [[TheClass allocWithZone:nil] init];

Do not override allocWithZone: to include any initialization code. Instead, class-specific versions of init... methods.

This method exists for historical reasons; memory zones are no longer used by Objective-C.

Availability
  • Available in iOS 2.0 and later.
Declared In
objc/NSObject.h

cancelPreviousPerformRequestsWithTarget:

Cancels perform requests previously registered with the performSelector:withObject:afterDelay: instance method.

+ (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget
Parameters
aTarget

The target for requests previously registered with the performSelector:withObject:afterDelay: instance method.

Discussion

All perform requests having the same target aTarget are canceled. This method removes perform requests only in the current run loop, not all run loops.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSRunLoop.h

cancelPreviousPerformRequestsWithTarget:selector:object:

Cancels perform requests previously registered with performSelector:withObject:afterDelay:.

+ (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget selector:(SEL)aSelector object:(id)anArgument
Parameters
aTarget

The target for requests previously registered with the performSelector:withObject:afterDelay: instance method

aSelector

The selector for requests previously registered with the performSelector:withObject:afterDelay: instance method.

anArgument

The argument for requests previously registered with the performSelector:withObject:afterDelay: instance method. Argument equality is determined using isEqual:, so the value need not be the same object that was passed originally. Pass nil to match a request for nil that was originally passed as the argument.

Discussion

All perform requests are canceled that have the same target as aTarget, argument as anArgument, and selector as aSelector. This method removes perform requests only in the current run loop, not all run loops.

Availability
  • Available in iOS 2.0 and later.
Related Sample Code
Declared In
NSRunLoop.h

class

Returns the class object.

+ (Class)class
Return Value

The class object.

Discussion

Refer to a class only by its name when it is the receiver of a message. In all other cases, the class object must be obtained through this or a similar method. For example, here SomeClass is passed as an argument to the isKindOfClass: method (declared in the NSObject protocol):

BOOL test = [self isKindOfClass:[SomeClass class]];
Availability
  • Available in iOS 2.0 and later.
See Also
Declared In
objc/NSObject.h

classFallbacksForKeyedArchiver

Overridden to return the names of classes that can be used to decode objects if their class is unavailable.

+ (NSArray *)classFallbacksForKeyedArchiver
Return Value

An array of NSString objects that specify the names of classes in preferred order for unarchiving

Discussion

NSKeyedArchiver calls this method and stores the result inside the archive. If the actual class of an object doesn’t exist at the time of unarchiving, NSKeyedUnarchiver goes through the stored list of classes and uses the first one that does exists as a substitute class for decoding the object. The default implementation of this method returns nil.

You can use this method if you introduce a new class into your application to provide some backwards compatibility in case the archive will be read on a system that does not have that class. Sometimes there may be another class which may work nearly as well as a substitute for the new class, and the archive keys and archived state for the new class can be carefully chosen (or compatibility written out) so that the object can be unarchived as the substitute class if necessary.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSKeyedArchiver.h

classForKeyedUnarchiver

Overridden by subclasses to substitute a new class during keyed unarchiving.

+ (Class)classForKeyedUnarchiver
Return Value

The class to substitute for the receiver during keyed unarchiving.

Discussion

During keyed unarchiving, instances of the receiver will be decoded as members of the returned class. This method overrides the results of the decoder’s class and instance name to class encoding tables.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSKeyedArchiver.h

conformsToProtocol:

Returns a Boolean value that indicates whether the receiver conforms to a given protocol.

+ (BOOL)conformsToProtocol:(Protocol *)aProtocol
Parameters
aProtocol

A protocol.

Return Value

YES if the receiver conforms to aProtocol, otherwise NO.

Discussion

A class is said to “conform to” a protocol if it adopts the protocol or inherits from another class that adopts it. Protocols are adopted by listing them within angle brackets after the interface declaration. For example, here MyClass adopts the (fictitious) AffiliationRequests and Normalization protocols:

@interface MyClass : NSObject <AffiliationRequests, Normalization>

A class also conforms to any protocols that are incorporated in the protocols it adopts or inherits. Protocols incorporate other protocols in the same way classes adopt them. For example, here the AffiliationRequests protocol incorporates the Joining protocol:

@protocol AffiliationRequests <Joining>

If a class adopts a protocol that incorporates another protocol, it must also implement all the methods in the incorporated protocol or inherit those methods from a class that adopts it.

This method determines conformance solely on the basis of the formal declarations in header files, as illustrated above. It doesn’t check to see whether the methods declared in the protocol are actually implemented—that’s the programmer’s responsibility.

The protocol required as this method’s argument can be specified using the @protocol() directive:

BOOL canJoin = [MyClass conformsToProtocol:@protocol(Joining)];
Availability
  • Available in iOS 2.0 and later.
Declared In
objc/NSObject.h

copyWithZone:

Returns the receiver.

+ (id)copyWithZone:(NSZone *)zone
Parameters
zone

This argument is ignored.

Return Value

The receiver.

Discussion

This method exists so class objects can be used in situations where you need an object that conforms to the NSCopying protocol. For example, this method lets you use a class object as a key to an NSDictionary object. You should not override this method.

Availability
  • Available in iOS 2.0 and later.
See Also
Declared In
objc/NSObject.h

description

Returns a string that represents the contents of the receiving class.

+ (NSString *)description
Return Value

A string that represents the contents of the receiving class.

Discussion

The debugger’s print-object command invokes this method to produce a textual description of an object.

NSObject's implementation of this method simply prints the name of the class.

Availability
  • Available in iOS 2.0 and later.
See Also
Declared In
objc/NSObject.h

initialize

Initializes the class before it receives its first message.

+ (void)initialize
Discussion

The runtime sends initialize to each class in a program just before the class, or any class that inherits from it, is sent its first message from within the program. The runtime sends the initialize message to classes in a thread-safe manner. Superclasses receive this message before their subclasses. The superclass implementation may be called multiple times if subclasses do not implement initialize—the runtime will call the inherited implementation—or if subclasses explicitly call [super initialize]. If you want to protect yourself from being run multiple times, you can structure your implementation along these lines:

+ (void)initialize {
  if (self == [ClassName self]) {
    // ... do the initialization ...
  }
}

Because initialize is called in a thread-safe manner and the order of initialize being called on different classes is not guaranteed, it’s important to do the minimum amount of work necessary in initialize methods. Specifically, any code that takes locks that might be required by other classes in their initialize methods is liable to lead to deadlocks. Therefore you should not rely on initialize for complex initialization, and should instead limit it to straightforward, class local initialization.

Special Considerations

initialize is invoked only once per class. If you want to perform independent initialization for the class and for categories of the class, you should implement load methods.

Availability
  • Available in iOS 2.0 and later.
See Also
Declared In
objc/NSObject.h

instanceMethodForSelector:

Locates and returns the address of the implementation of the instance method identified by a given selector.

+ (IMP)instanceMethodForSelector:(SEL)aSelector
Parameters
aSelector

A selector that identifies the method for which to return the implementation address. The selector must be non-NULL and valid for the receiver. If in doubt, use the respondsToSelector: method to check before passing the selector to methodForSelector:.

Return Value

The address of the implementation of the aSelector instance method.

Discussion

An error is generated if instances of the receiver can’t respond to aSelector messages.

Use this method to ask the class object for the implementation of instance methods only. To ask the class for the implementation of a class method, send the methodForSelector: instance method to the class instead.

Availability
  • Available in iOS 2.0 and later.
Declared In
objc/NSObject.h

instanceMethodSignatureForSelector:

Returns an NSMethodSignature object that contains a description of the instance method identified by a given selector.

+ (NSMethodSignature *)instanceMethodSignatureForSelector:(SEL)aSelector
Parameters
aSelector

A selector that identifies the method for which to return the implementation address.

Return Value

An NSMethodSignature object that contains a description of the instance method identified by aSelector, or nil if the method can’t be found.

Availability
  • Available in iOS 2.0 and later.
Declared In
objc/NSObject.h

instancesRespondToSelector:

Returns a Boolean value that indicates whether instances of the receiver are capable of responding to a given selector.

+ (BOOL)instancesRespondToSelector:(SEL)aSelector
Parameters
aSelector

A selector.

Return Value

YES if instances of the receiver are capable of responding to aSelector messages, otherwise NO.

Discussion

If aSelector messages are forwarded to other objects, instances of the class are able to receive those messages without error even though this method returns NO.

To ask the class whether it, rather than its instances, can respond to a particular message, send to the class instead the NSObject protocol instance method respondsToSelector:.

Availability
  • Available in iOS 2.0 and later.
Declared In
objc/NSObject.h

isSubclassOfClass:

Returns a Boolean value that indicates whether the receiving class is a subclass of, or identical to, a given class.

+ (BOOL)isSubclassOfClass:(Class)aClass
Parameters
aClass

A class object.

Return Value

YES if the receiving class is a subclass of—or identical to—aClass, otherwise NO.

Availability
  • Available in iOS 2.0 and later.
Declared In
objc/NSObject.h

load

Invoked whenever a class or category is added to the Objective-C runtime; implement this method to perform class-specific behavior upon loading.

+ (void)load
Discussion

The load message is sent to classes and categories that are both dynamically loaded and statically linked, but only if the newly loaded class or category implements a method that can respond.

The order of initialization is as follows:

  1. All initializers in any framework you link to.

  2. All +load methods in your image.

  3. All C++ static initializers and C/C++ __attribute__(constructor) functions in your image.

  4. All initializers in frameworks that link to you.

In addition:

  • A class’s +load method is called after all of its superclasses’ +load methods.

  • A category +load method is called after the class’s own +load method.

In a custom implementation of load you can therefore safely message other unrelated classes from the same image, but any load methods implemented by those classes may not have run yet.

Availability
  • Available in iOS 2.0 and later.
See Also
Declared In
objc/NSObject.h

mutableCopyWithZone:

Returns the receiver.

+ (id)mutableCopyWithZone:(NSZone *)zone
Parameters
zone

The memory zone in which to create the copy of the receiver.

Return Value

The receiver.

Discussion

This method exists so class objects can be used in situations where you need an object that conforms to the NSMutableCopying protocol. For example, this method lets you use a class object as a key to an NSDictionary object. You should not override this method.

Availability
  • Available in iOS 2.0 and later.
Declared In
objc/NSObject.h

new

Allocates a new instance of the receiving class, sends it an init message, and returns the initialized object.

+ (id)new
Return Value

A new instance of the receiver.

Discussion

This method is a combination of alloc and init. Like alloc, it initializes the isa instance variable of the new object so it points to the class data structure. It then invokes the init method to complete the initialization process.

Availability
  • Available in iOS 2.0 and later.
Declared In
objc/NSObject.h

resolveClassMethod:

Dynamically provides an implementation for a given selector for a class method.

+ (BOOL)resolveClassMethod:(SEL)name
Parameters
name

The name of a selector to resolve.

Return Value

YES if the method was found and added to the receiver, otherwise NO.

Discussion

This method allows you to dynamically provide an implementation for a given selector. See resolveInstanceMethod: for further discussion.

Availability
  • Available in iOS 2.0 and later.
Declared In
objc/NSObject.h

resolveInstanceMethod:

Dynamically provides an implementation for a given selector for an instance method.

+ (BOOL)resolveInstanceMethod:(SEL)name
Parameters
name

The name of a selector to resolve.

Return Value

YES if the method was found and added to the receiver, otherwise NO.

Discussion

This method and resolveClassMethod: allow you to dynamically provide an implementation for a given selector.

An Objective-C method is simply a C function that take at least two arguments—self and _cmd. Using the class_addMethod function, you can add a function to a class as a method. Given the following function:

void dynamicMethodIMP(id self, SEL _cmd)
{
    // implementation ....
}

you can use resolveInstanceMethod: to dynamically add it to a class as a method (called resolveThisMethodDynamically) like this:

+ (BOOL) resolveInstanceMethod:(SEL)aSEL
{
    if (aSEL == @selector(resolveThisMethodDynamically))
    {
          class_addMethod([self class], aSEL, (IMP) dynamicMethodIMP, "v@:");
          return YES;
    }
    return [super resolveInstanceMethod:aSel];
}
Special Considerations

This method is called before the Objective-C forwarding mechanism is invoked. If respondsToSelector: or instancesRespondToSelector: is invoked, the dynamic method resolver is given the opportunity to provide an IMP for the given selector first.

Availability
  • Available in iOS 2.0 and later.
Declared In
objc/NSObject.h

setVersion:

Sets the receiver's version number.

+ (void)setVersion:(NSInteger)aVersion
Parameters
aVersion

The version number for the receiver.

Discussion

The version number is helpful when instances of the class are to be archived and reused later. The default version is 0.

Special Considerations

The version number applies to NSArchiver/NSUnarchiver, but not to NSKeyedArchiver/NSKeyedUnarchiver. A keyed archiver does not encode class version numbers.

Availability
  • Available in iOS 2.0 and later.
See Also
Declared In
NSObject.h

superclass

Returns the class object for the receiver’s superclass.

+ (Class)superclass
Return Value

The class object for the receiver’s superclass.

Availability
  • Available in iOS 2.0 and later.
See Also
Declared In
objc/NSObject.h

version

Returns the version number assigned to the class.

+ (NSInteger)version
Return Value

The version number assigned to the class.

Discussion

If no version has been set, the default is 0.

Version numbers are needed for decoding or unarchiving, so older versions of an object can be detected and decoded correctly.

Caution should be taken when obtaining the version from within an NSCoding protocol or other methods. Use the class name explicitly when getting a class version number:

version = [MyClass version];

Don’t simply send version to the return value of class—a subclass version number may be returned instead.

Special Considerations

The version number applies to NSArchiver/NSUnarchiver, but not to NSKeyedArchiver/NSKeyedUnarchiver. A keyed archiver does not encode class version numbers.

Availability
  • Available in iOS 2.0 and later.
Related Sample Code
Declared In
NSObject.h

Instance Methods

autoContentAccessingProxy

Creates and returns a proxy for the receiving object

- (id)autoContentAccessingProxy
Return Value

A proxy of the receiver.

Discussion

This method creates and returns a proxy for the receiving object if the receiver adopts the NSDiscardableContent protocol and still has content that has not been discarded.

The proxy calls beginContentAccess on the receiver to keep the content available as long as the proxy lives, and calls endContentAccess when the proxy is deallocated.

The wrapper object is otherwise a subclass of NSProxy and forwards messages to the original receiver object as an NSProxy does.

This method can be used to hide an NSDiscardableContent object's content volatility by creating an object that responds to the same messages but holds the contents of the original receiver available as long as the created proxy lives. Thus hidden, the NSDiscardableContent object (by way of the proxy) can be given out to unsuspecting recipients of the object who would otherwise not know they might have to call beginContentAccess and endContentAccess around particular usages (specific to each NSDiscardableContent object) of the NSDiscardableContent object.

Availability
  • Available in iOS 4.0 and later.
Declared In
NSObject.h

awakeAfterUsingCoder:

Overridden by subclasses to substitute another object in place of the object that was decoded and subsequently received this message.

- (id)awakeAfterUsingCoder:(NSCoder *)aDecoder
Parameters
aDecoder

The decoder used to decode the receiver.

Return Value

The receiver, or another object to take the place of the object that was decoded and subsequently received this message.

Discussion

You can use this method to eliminate redundant objects created by the coder. For example, if after decoding an object you discover that an equivalent object already exists, you can return the existing object. If a replacement is returned, your overriding method is responsible for releasing the receiver.

This method is invoked by NSCoder. NSObject’s implementation simply returns self.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSObject.h

classForCoder

Overridden by subclasses to substitute a class other than its own during coding.

- (Class)classForCoder
Return Value

The class to substitute for the receiver's own class during coding.

Discussion

This method is invoked by NSCoder. NSObject’s implementation returns the receiver’s class. The private subclasses of a class cluster substitute the name of their public superclass when being archived.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSObject.h

classForKeyedArchiver

Overridden by subclasses to substitute a new class for instances during keyed archiving.

- (Class)classForKeyedArchiver
Discussion

The object will be encoded as if it were a member of the returned class. The results of this method are overridden by the encoder class and instance name to class encoding tables. If nil is returned, the result of this method is ignored.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSKeyedArchiver.h

copy

Returns the object returned by copyWithZone:.

- (id)copy
Return Value

The object returned by the NSCopying protocol method copyWithZone:,.

Discussion

This is a convenience method for classes that adopt the NSCopying protocol. An exception is raised if there is no implementation for copyWithZone:.

NSObject does not itself support the NSCopying protocol. Subclasses must support the protocol and implement the copyWithZone: method. A subclass version of the copyWithZone: method should send the message to super first, to incorporate its implementation, unless the subclass descends directly from NSObject.

Availability
  • Available in iOS 2.0 and later.
Declared In
objc/NSObject.h

dealloc

Deallocates the memory occupied by the receiver.

- (void)dealloc
Discussion

Subsequent messages to the receiver may generate an error indicating that a message was sent to a deallocated object (provided the deallocated memory hasn’t been reused yet).

You override this method to dispose of resources other than the object’s instance variables, for example:

- (void)dealloc {
    free(myBigBlockOfMemory);
}

In an implementation of dealloc, do not invoke the superclass’s implementation. You should try to avoid managing the lifetime of limited resources such as file descriptors using dealloc.

You never send a dealloc message directly. Instead, an object’s dealloc method is invoked by the runtime. See Advanced Memory Management Programming Guide for more details.

Special Considerations

When not using ARC, your implementation of dealloc must invoke the superclass’s implementation as its last instruction.

Availability
  • Available in iOS 2.0 and later.
Declared In
objc/NSObject.h

doesNotRecognizeSelector:

Handles messages the receiver doesn’t recognize.

- (void)doesNotRecognizeSelector:(SEL)aSelector
Parameters
aSelector

A selector that identifies a method not implemented or recognized by the receiver.

Discussion

The runtime system invokes this method whenever an object receives an aSelector message it can’t respond to or forward. This method, in turn, raises an NSInvalidArgumentException, and generates an error message.

Any doesNotRecognizeSelector: messages are generally sent only by the runtime system. However, they can be used in program code to prevent a method from being inherited. For example, an NSObject subclass might renounce the copy or init method by re-implementing it to include a doesNotRecognizeSelector: message as follows:

- (id)copy
{
    [self doesNotRecognizeSelector:_cmd];
}

The _cmd variable is a hidden argument passed to every method that is the current selector; in this example, it identifies the selector for the copy method. This code prevents instances of the subclass from responding to copy messages or superclasses from forwarding copy messages—although respondsToSelector: will still report that the receiver has access to a copy method.

If you override this method, you must call super or raise an NSInvalidArgumentException exception at the end of your implementation. In other words, this method must not return normally; it must always result in an exception being thrown.

Availability
  • Available in iOS 2.0 and later.
Declared In
objc/NSObject.h

finalize

The garbage collector invokes this method on the receiver before disposing of the memory it uses. (Deprecated. Garbage collection is deprecated in OS X v10.8; instead, you should use Automatic Reference Counting—see Transitioning to ARC Release Notes.)

- (void)finalize
Discussion

The garbage collector invokes this method on the receiver before disposing of the memory it uses. When garbage collection is enabled, this method is invoked instead of dealloc.

You can override this method to relinquish resources the receiver has obtained, as shown in the following example:

- (void)finalize {
    if (log_file != NULL) {
        fclose(log_file);
        log_file = NULL;
    }
    [super finalize];
}

Typically, however, you are encouraged to relinquish resources prior to finalization if at all possible. For more details, see “Implementing a finalize Method”.

Special Considerations

It is an error to store self into a new or existing live object (colloquially known as “resurrection”), which implies that this method will be called only once. However, the receiver may be messaged after finalization by other objects also being finalized at this time, so your override should guard against future use of resources that have been reclaimed, as shown by the log_file = NULL statement in the example. The finalize method itself will never be invoked more than once for a given object.

Availability
  • Available in iOS 2.0 and later.
See Also
Declared In
objc/NSObject.h

forwardingTargetForSelector:

Returns the object to which unrecognized messages should first be directed.

- (id)forwardingTargetForSelector:(SEL)aSelector
Parameters
aSelector

A selector for a method that the receiver does not implement.

Return Value

The object to which unrecognized messages should first be directed.

Discussion

If an object implements (or inherits) this method, and returns a non-nil (and non-self) result, that returned object is used as the new receiver object and the message dispatch resumes to that new object. (Obviously if you return self from this method, the code would just fall into an infinite loop.)

If you implement this method in a non-root class, if your class has nothing to return for the given selector then you should return the result of invoking super’s implementation.

This method gives an object a chance to redirect an unknown message sent to it before the much more expensive forwardInvocation: machinery takes over. This is useful when you simply want to redirect messages to another object and can be an order of magnitude faster than regular forwarding. It is not useful where the goal of the forwarding is to capture the NSInvocation, or manipulate the arguments or return value during the forwarding.

Availability
  • Available in iOS 2.0 and later.
Declared In
objc/NSObject.h

forwardInvocation:

Overridden by subclasses to forward messages to other objects.

- (void)forwardInvocation:(NSInvocation *)anInvocation
Parameters
anInvocation

The invocation to forward.

Discussion

When an object is sent a message for which it has no corresponding method, the runtime system gives the receiver an opportunity to delegate the message to another receiver. It delegates the message by creating an NSInvocation object representing the message and sending the receiver a forwardInvocation: message containing this NSInvocation object as the argument. The receiver’s forwardInvocation: method can then choose to forward the message to another object. (If that object can’t respond to the message either, it too will be given a chance to forward it.)

The forwardInvocation: message thus allows an object to establish relationships with other objects that will, for certain messages, act on its behalf. The forwarding object is, in a sense, able to “inherit” some of the characteristics of the object it forwards the message to.

An implementation of the forwardInvocation: method has two tasks:

  • To locate an object that can respond to the message encoded in anInvocation. This object need not be the same for all messages.

  • To send the message to that object using anInvocation. anInvocation will hold the result, and the runtime system will extract and deliver this result to the original sender.

In the simple case, in which an object forwards messages to just one destination (such as the hypothetical friend instance variable in the example below), a forwardInvocation: method could be as simple as this:

- (void)forwardInvocation:(NSInvocation *)invocation
{
    SEL aSelector = [invocation selector];
 
    if ([friend respondsToSelector:aSelector])
        [invocation invokeWithTarget:friend];
    else
        [super forwardInvocation:invocation];
}

The message that’s forwarded must have a fixed number of arguments; variable numbers of arguments (in the style of printf()) are not supported.

The return value of the forwarded message is returned to the original sender. All types of return values can be delivered to the sender: id types, structures, double-precision floating-point numbers.

Implementations of the forwardInvocation: method can do more than just forward messages. forwardInvocation: can, for example, be used to consolidate code that responds to a variety of different messages, thus avoiding the necessity of having to write a separate method for each selector. A forwardInvocation: method might also involve several other objects in the response to a given message, rather than forward it to just one.

NSObject’s implementation of forwardInvocation: simply invokes the doesNotRecognizeSelector: method; it doesn’t forward any messages. Thus, if you choose not to implement forwardInvocation:, sending unrecognized messages to objects will raise exceptions.

Availability
  • Available in iOS 2.0 and later.
Declared In
objc/NSObject.h

init

Implemented by subclasses to initialize a new object (the receiver) immediately after memory for it has been allocated.

- (id)init
Return Value

An initialized object, or nil if an object could not be created for some reason that would not result in an exception.

Discussion

An init message is coupled with an alloc (or allocWithZone:) message in the same line of code:

TheClass *newObject = [[TheClass alloc] init];

An object isn’t ready to be used until it has been initialized. The init method defined in the NSObject class does no initialization; it simply returns self.

In a custom implementation of this method, you must invoke super’s designated initializer then initialize and return the new object. If the new object can’t be initialized, the method should return nil. For example, a hypothetical BuiltInCamera class might return nil from its init method if run on a device that has no camera.

- (id)init {
    self = [super init];
    if (self) {
        // Initialize self.
    }
    return self;
}

In some cases, an init method might return a substitute object. You must therefore always use the object returned by init, and not the one returned by alloc or allocWithZone:, in subsequent code.

Availability
  • Available in iOS 2.0 and later.
Declared In
objc/NSObject.h

methodForSelector:

Locates and returns the address of the receiver’s implementation of a method so it can be called as a function.

- (IMP)methodForSelector:(SEL)aSelector
Parameters
aSelector

A selector that identifies the method for which to return the implementation address. The selector must be a valid and non-NULL. If in doubt, use the respondsToSelector: method to check before passing the selector to methodForSelector:.

Return Value

The address of the receiver’s implementation of the aSelector.

Discussion

If the receiver is an instance, aSelector should refer to an instance method; if the receiver is a class, it should refer to a class method.

Availability
  • Available in iOS 2.0 and later.
Declared In
objc/NSObject.h

methodSignatureForSelector:

Returns an NSMethodSignature object that contains a description of the method identified by a given selector.

- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
Parameters
aSelector

A selector that identifies the method for which to return the implementation address. When the receiver is an instance, aSelector should identify an instance method; when the receiver is a class, it should identify a class method.

Return Value

An NSMethodSignature object that contains a description of the method identified by aSelector, or nil if the method can’t be found.

Discussion

This method is used in the implementation of protocols. This method is also used in situations where an NSInvocation object must be created, such as during message forwarding. If your object maintains a delegate or is capable of handling messages that it does not directly implement, you should override this method to return an appropriate method signature.

Availability
  • Available in iOS 2.0 and later.
Declared In
objc/NSObject.h

mutableCopy

Returns the object returned by mutableCopyWithZone: where the zone is nil.

- (id)mutableCopy
Return Value

The object returned by the NSMutableCopying protocol method mutableCopyWithZone:, where the zone is nil.

Discussion

This is a convenience method for classes that adopt the NSMutableCopying protocol. An exception is raised if there is no implementation for mutableCopyWithZone:.

Availability
  • Available in iOS 2.0 and later.
Declared In
objc/NSObject.h

performSelector:onThread:withObject:waitUntilDone:

Invokes a method of the receiver on the specified thread using the default mode.

- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thread withObject:(id)arg waitUntilDone:(BOOL)wait
Parameters
aSelector

A selector that identifies the method to invoke. The method should not have a significant return value and should take a single argument of type id, or no arguments.

thread

The thread on which to execute aSelector.

arg

The argument to pass to the method when it is invoked. Pass nil if the method does not take an argument.

wait

A Boolean that specifies whether the current thread blocks until after the specified selector is performed on the receiver on the specified thread. Specify YES to block this thread; otherwise, specify NO to have this method return immediately.

If the current thread and target thread are the same, and you specify YES for this parameter, the selector is performed immediately on the current thread. If you specify NO, this method queues the message on the thread’s run loop and returns, just like it does for other threads. The current thread must then dequeue and process the message when it has an opportunity to do so.

Discussion

You can use this method to deliver messages to other threads in your application. The message in this case is a method of the current object that you want to execute on the target thread.

This method queues the message on the run loop of the target thread using the default run loop modes—that is, the modes associated with the NSRunLoopCommonModes constant. As part of its normal run loop processing, the target thread dequeues the message (assuming it is running in one of the default run loop modes) and invokes the desired method.

You cannot cancel messages queued using this method. If you want the option of canceling a message on the current thread, you must use either the performSelector:withObject:afterDelay: or performSelector:withObject:afterDelay:inModes: method.

Special Considerations

This method registers with the runloop of its current context, and depends on that runloop being run on a regular basis to perform correctly. One common context where you might call this method and end up registering with a runloop that is not automatically run on a regular basis is when being invoked by a dispatch queue. If you need this type of functionality when running on a dispatch queue, you should use dispatch_after and related methods to get the behavior you want.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSThread.h

performSelector:onThread:withObject:waitUntilDone:modes:

Invokes a method of the receiver on the specified thread using the specified modes.

- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thread withObject:(id)arg waitUntilDone:(BOOL)wait modes:(NSArray *)array
Parameters
aSelector

A selector that identifies the method to invoke. It should not have a significant return value and should take a single argument of type id, or no arguments.

thread

The thread on which to execute aSelector. This thread represents the target thread.

arg

The argument to pass to the method when it is invoked. Pass nil if the method does not take an argument.

wait

A Boolean that specifies whether the current thread blocks until after the specified selector is performed on the receiver on the specified thread. Specify YES to block this thread; otherwise, specify NO to have this method return immediately.

If the current thread and target thread are the same, and you specify YES for this parameter, the selector is performed immediately. If you specify NO, this method queues the message and returns immediately, regardless of whether the threads are the same or different.

array

An array of strings that identifies the modes in which it is permissible to perform the specified selector. This array must contain at least one string. If you specify nil or an empty array for this parameter, this method returns without performing the specified selector. For information about run loop modes, see “Run Loops” in Threading Programming Guide.

Discussion

You can use this method to deliver messages to other threads in your application. The message in this case is a method of the current object that you want to execute on the target thread.

This method queues the message on the run loop of the target thread using the run loop modes specified in the array parameter. As part of its normal run loop processing, the target thread dequeues the message (assuming it is running in one of the specified modes) and invokes the desired method.

You cannot cancel messages queued using this method. If you want the option of canceling a message on the current thread, you must use either the performSelector:withObject:afterDelay: or performSelector:withObject:afterDelay:inModes: method instead.

Special Considerations

This method registers with the runloop of its current context, and depends on that runloop being run on a regular basis to perform correctly. One common context where you might call this method and end up registering with a runloop that is not automatically run on a regular basis is when being invoked by a dispatch queue. If you need this type of functionality when running on a dispatch queue, you should use dispatch_after and related methods to get the behavior you want.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSThread.h

performSelector:withObject:afterDelay:

Invokes a method of the receiver on the current thread using the default mode after a delay.

- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay
Parameters
aSelector

A selector that identifies the method to invoke. The method should not have a significant return value and should take a single argument of type id, or no arguments.

anArgument

The argument to pass to the method when it is invoked. Pass nil if the method does not take an argument.

delay

The minimum time before which the message is sent. Specifying a delay of 0 does not necessarily cause the selector to be performed immediately. The selector is still queued on the thread’s run loop and performed as soon as possible.

Discussion

This method sets up a timer to perform the aSelector message on the current thread’s run loop. The timer is configured to run in the default mode (NSDefaultRunLoopMode). When the timer fires, the thread attempts to dequeue the message from the run loop and perform the selector. It succeeds if the run loop is running and in the default mode; otherwise, the timer waits until the run loop is in the default mode.

If you want the message to be dequeued when the run loop is in a mode other than the default mode, use the performSelector:withObject:afterDelay:inModes: method instead. If you are not sure whether the current thread is the main thread, you can use the performSelectorOnMainThread:withObject:waitUntilDone: or performSelectorOnMainThread:withObject:waitUntilDone:modes: method to guarantee that your selector executes on the main thread. To cancel a queued message, use the cancelPreviousPerformRequestsWithTarget: or cancelPreviousPerformRequestsWithTarget:selector:object: method.

Special Considerations

This method registers with the runloop of its current context, and depends on that runloop being run on a regular basis to perform correctly. One common context where you might call this method and end up registering with a runloop that is not automatically run on a regular basis is when being invoked by a dispatch queue. If you need this type of functionality when running on a dispatch queue, you should use dispatch_after and related methods to get the behavior you want.

Availability
  • Available in iOS 2.0 and later.
Related Sample Code
Declared In
NSRunLoop.h

performSelector:withObject:afterDelay:inModes:

Invokes a method of the receiver on the current thread using the specified modes after a delay.

- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay inModes:(NSArray *)modes
Parameters
aSelector

A selector that identifies the method to invoke. The method should not have a significant return value and should take a single argument of type id, or no arguments.

anArgument

The argument to pass to the method when it is invoked. Pass nil if the method does not take an argument.

delay

The minimum time before which the message is sent. Specifying a delay of 0 does not necessarily cause the selector to be performed immediately. The selector is still queued on the thread’s run loop and performed as soon as possible.

modes

An array of strings that identify the modes to associate with the timer that performs the selector. This array must contain at least one string. If you specify nil or an empty array for this parameter, this method returns without performing the specified selector. For information about run loop modes, see “Run Loops” in Threading Programming Guide.

Discussion

This method sets up a timer to perform the aSelector message on the current thread’s run loop. The timer is configured to run in the modes specified by the modes parameter. When the timer fires, the thread attempts to dequeue the message from the run loop and perform the selector. It succeeds if the run loop is running and in one of the specified modes; otherwise, the timer waits until the run loop is in one of those modes.

If you want the message to be dequeued when the run loop is in a mode other than the default mode, use the performSelector:withObject:afterDelay:inModes: method instead. If you are not sure whether the current thread is the main thread, you can use the performSelectorOnMainThread:withObject:waitUntilDone: or performSelectorOnMainThread:withObject:waitUntilDone:modes: method to guarantee that your selector executes on the main thread. To cancel a queued message, use the cancelPreviousPerformRequestsWithTarget: or cancelPreviousPerformRequestsWithTarget:selector:object: method.

Special Considerations

This method registers with the runloop of its current context, and depends on that runloop being run on a regular basis to perform correctly. One common context where you might call this method and end up registering with a runloop that is not automatically run on a regular basis is when being invoked by a dispatch queue. If you need this type of functionality when running on a dispatch queue, you should use dispatch_after and related methods to get the behavior you want.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSRunLoop.h

performSelectorInBackground:withObject:

Invokes a method of the receiver on a new background thread.

- (void)performSelectorInBackground:(SEL)aSelector withObject:(id)arg
Parameters
aSelector

A selector that identifies the method to invoke. The method should not have a significant return value and should take a single argument of type id, or no arguments.

arg

The argument to pass to the method when it is invoked. Pass nil if the method does not take an argument.

Discussion

This method creates a new thread in your application, putting your application into multithreaded mode if it was not already. The method represented by aSelector must set up the thread environment just as you would for any other new thread in your program. For more information about how to configure and run threads, see Threading Programming Guide.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSThread.h

performSelectorOnMainThread:withObject:waitUntilDone:

Invokes a method of the receiver on the main thread using the default mode.

- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait
Parameters
aSelector

A selector that identifies the method to invoke. The method should not have a significant return value and should take a single argument of type id, or no arguments.

arg

The argument to pass to the method when it is invoked. Pass nil if the method does not take an argument.

wait

A Boolean that specifies whether the current thread blocks until after the specified selector is performed on the receiver on the main thread. Specify YES to block this thread; otherwise, specify NO to have this method return immediately.

If the current thread is also the main thread, and you specify YES for this parameter, the message is delivered and processed immediately.

Discussion

You can use this method to deliver messages to the main thread of your application. The main thread encompasses the application’s main run loop, and is where the NSApplication object receives events. The message in this case is a method of the current object that you want to execute on the thread.

This method queues the message on the run loop of the main thread using the common run loop modes—that is, the modes associated with the NSRunLoopCommonModes constant. As part of its normal run loop processing, the main thread dequeues the message (assuming it is running in one of the common run loop modes) and invokes the desired method. Multiple calls to this method from the same thread cause the corresponding selectors to be queued and performed in the same same order in which the calls were made.

You cannot cancel messages queued using this method. If you want the option of canceling a message on the current thread, you must use either the performSelector:withObject:afterDelay: or performSelector:withObject:afterDelay:inModes: method.

Special Considerations

This method registers with the runloop of its current context, and depends on that runloop being run on a regular basis to perform correctly. One common context where you might call this method and end up registering with a runloop that is not automatically run on a regular basis is when being invoked by a dispatch queue. If you need this type of functionality when running on a dispatch queue, you should use dispatch_after and related methods to get the behavior you want.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSThread.h

performSelectorOnMainThread:withObject:waitUntilDone:modes:

Invokes a method of the receiver on the main thread using the specified modes.

- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait modes:(NSArray *)array
Parameters
aSelector

A selector that identifies the method to invoke. The method should not have a significant return value and should take a single argument of type id, or no arguments.

arg

The argument to pass to the method when it is invoked. Pass nil if the method does not take an argument.

wait

A Boolean that specifies whether the current thread blocks until after the specified selector is performed on the receiver on the main thread. Specify YES to block this thread; otherwise, specify NO to have this method return immediately.

If the current thread is also the main thread, and you pass YES, the message is performed immediately, otherwise the perform is queued to run the next time through the run loop.

array

An array of strings that identifies the modes in which it is permissible to perform the specified selector. This array must contain at least one string. If you specify nil or an empty array for this parameter, this method returns without performing the specified selector. For information about run loop modes, see “Run Loops” in Threading Programming Guide.

Discussion

You can use this method to deliver messages to the main thread of your application. The main thread encompasses the application’s main run loop, and is where the NSApplication object receives events. The message in this case is a method of the current object that you want to execute on the thread.

This method queues the message on the run loop of the main thread using the run loop modes specified in the array parameter. As part of its normal run loop processing, the main thread dequeues the message (assuming it is running in one of the specified modes) and invokes the desired method. Multiple calls to this method from the same thread cause the corresponding selectors to be queued and performed in the same same order in which the calls were made, assuming the associated run loop modes for each selector are the same. If you specify different modes for each selector, any selectors whose associated mode does not match the current run loop mode are skipped until the run loop subsequently executes in that mode.

You cannot cancel messages queued using this method. If you want the option of canceling a message on the current thread, you must use either the performSelector:withObject:afterDelay: or performSelector:withObject:afterDelay:inModes: method.

Special Considerations

This method registers with the runloop of its current context, and depends on that runloop being run on a regular basis to perform correctly. One common context where you might call this method and end up registering with a runloop that is not automatically run on a regular basis is when being invoked by a dispatch queue. If you need this type of functionality when running on a dispatch queue, you should use dispatch_after and related methods to get the behavior you want.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSThread.h

replacementObjectForCoder:

Overridden by subclasses to substitute another object for itself during encoding.

- (id)replacementObjectForCoder:(NSCoder *)aCoder
Parameters
aCoder

The coder encoding the receiver.

Return Value

The object encode instead of the receiver (if different).

Discussion

An object might encode itself into an archive, but encode a proxy for itself if it’s being encoded for distribution. This method is invoked by NSCoder. NSObject’s implementation returns self.

Availability
  • Available in iOS 2.0 and later.
Declared In
NSObject.h

replacementObjectForKeyedArchiver:

Overridden by subclasses to substitute another object for itself during keyed archiving.

- (id)replacementObjectForKeyedArchiver:(NSKeyedArchiver *)archiver
Parameters
archiver

A keyed archiver creating an archive.

Return Value

The object encode instead of the receiver (if different).

Discussion

This method is called only if no replacement mapping for the object has been set up in the encoder (for example, due to a previous call of replacementObjectForKeyedArchiver: to that object).

Availability
  • Available in iOS 2.0 and later.
Declared In
NSKeyedArchiver.h