| Inherits from | none (NSObject is a root class) |
| Conforms to | |
| Framework | /System/Library/Frameworks/Foundation.framework |
| Availability | Available in iPhone OS 2.0 and later. |
| Companion guide | |
| Declared in | NSKeyedArchiver.h NSObject.h NSRunLoop.h NSThread.h |
| Related sample code |
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.
NSObject has some special methods that take advantage of the Objective-C runtime system. For example, you can ask a class or instance if it responds to a message before invoking a particular method. You can also ask for a method implementation and invoke it using one of the perform... methods, or as a function, although this is typically discouraged since it circumvents dynamic binding.
These and other NSObject methods take a selector of type SEL as an argument. For efficiency, full ASCII names are not used to represent methods in compiled code. Instead the compiler uses a unique identifier to represent a method at runtime called a selector. A selector for a method name is obtained using the @selector() directive:
SEL method = @selector(isEqual:); |
The instanceMethodForSelector: class method and the methodForSelector: instance method return a method implementation of type IMP. IMP is defined as a pointer to a function that returns an id and takes a variable number of arguments (in addition to the two “hidden” arguments—self and _cmd—that are passed to every method implementation):
typedef id (*IMP)(id, SEL, ...); |
This definition serves as a prototype for the function pointer returned by these methods. It’s sufficient for methods that return an object and take object arguments. However, if the selector takes different argument types or returns anything but an id, its function counterpart will be inadequately prototyped. Lacking a prototype, the compiler will promote floats to doubles and chars to ints, which the implementation won’t expect. It will therefore behave differently (and erroneously) when performed as a method.
To remedy this situation, it’s necessary to provide your own prototype. In the example below, the declaration of the test variable serves to prototype the implementation of the isEqual: method. test is defined as a pointer to a function that returns a BOOL and takes an id argument (in addition to the two “hidden” arguments). The value returned by methodForSelector: is then similarly cast to be a pointer to this same function type:
BOOL (*test)(id, SEL, id); |
test = (BOOL (*)(id, SEL, id))[target methodForSelector:@selector(isEqual:)]; |
while ( !test(target, @selector(isEqual:), someObject) ) { |
... |
} |
In some cases, it might be clearer to define a type (similar to IMP) that can be used both for declaring the variable and for casting the function pointer methodForSelector: returns. The example below defines the EqualIMP type for just this purpose:
typedef BOOL (*EqualIMP)(id, SEL, id); |
EqualIMP test; |
test = (EqualIMP)[target methodForSelector:@selector(isEqual:)]; |
while ( !test(target, @selector(isEqual:), someObject) ) { |
... |
} |
Either way, it’s important to cast the return value of methodForSelector: to the appropriate function type. It’s not sufficient to simply call the function returned by methodForSelector: and cast the result of that call to the desired type. Doing so can result in errors.
See Messaging in Objective-C Runtime Programming Guide for more information.
+ new
+ alloc
+ allocWithZone:
– init
– copy
+ copyWithZone:
– mutableCopy
+ mutableCopyWithZone:
– dealloc
– finalize
– methodForSelector:
+ instanceMethodForSelector:
+ instanceMethodSignatureForSelector:
– methodSignatureForSelector:
– performSelector:withObject:afterDelay:
– performSelector:withObject:afterDelay:inModes:
– performSelectorOnMainThread:withObject:waitUntilDone:
– performSelectorOnMainThread:withObject:waitUntilDone:modes:
– performSelector:onThread:withObject:waitUntilDone:
– performSelector:onThread:withObject:waitUntilDone:modes:
– performSelectorInBackground:withObject:
+ cancelPreviousPerformRequestsWithTarget:
+ cancelPreviousPerformRequestsWithTarget:selector:object:
Returns a new instance of the receiving class.
+ (id)alloc
A new instance of the receiver.
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. The new instance is allocated from the default zone—use allocWithZone: to specify a particular zone.
An init... method must be used to complete the initialization process. For example:
TheClass *newObject = [[TheClass alloc] init]; |
Subclasses shouldn’t override alloc to include initialization code. Instead, class-specific versions of init... methods should be implemented for that purpose. Class methods can also be implemented to combine allocation and initialization, similar to the new class method.
If you are using managed memory (not garbage collection), this method retains the object before returning it. The returned object has a retain count of 1 and is not autoreleased. The invoker of this method is responsible for releasing the returned object, using either release or autorelease.
NSObject.hReturns a new instance of the receiving class where memory for the new instance is allocated from a given zone.
+ (id)allocWithZone:(NSZone *)zone
The memory zone in which to create the new instance.
A new instance of the receiver, where memory for the new instance is allocated from zone.
The isa instance variable of the new instance is initialized to a data structure that describes the class; memory for its other instance variables is set to 0. If zone is nil, the new instance will be allocated from the default zone (as returned by NSDefaultMallocZone).
An init... method must be used to complete the initialization process. For example:
TheClass *newObject = [[TheClass allocWithZone:someZone] init]; |
Subclasses shouldn’t override allocWithZone: to include any initialization code. Instead, class-specific versions of init... methods should be implemented for that purpose.
When one object creates another, it’s sometimes a good idea to make sure they’re both allocated from the same region of memory. The zone method (declared in the NSObject protocol) can be used for this purpose; it returns the zone where the receiver is located. For example:
id myCompanion = [[TheClass allocWithZone:[self zone]] init]; |
If you are using managed memory (not garbage collection), this method retains the object before returning it. The returned object has a retain count of 1 and is not autoreleased. The invoker of this method is responsible for releasing the returned object, using either release or autorelease.
NSObject.hCancels perform requests previously registered with the performSelector:withObject:afterDelay: instance method.
+ (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget
The target for requests previously registered with the performSelector:withObject:afterDelay: instance method.
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.
NSRunLoop.hCancels perform requests previously registered with performSelector:withObject:afterDelay:.
+ (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget selector:(SEL)aSelector object:(id)anArgument
The target for requests previously registered with the performSelector:withObject:afterDelay: instance method
The selector for requests previously registered with the performSelector:withObject:afterDelay: instance method.
See “Selectors” for a description of the SEL type.
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.
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.
NSRunLoop.hReturns the class object.
+ (Class)class
The class object.
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]]; |
class (NSObject protocol)NSObject.hOverridden to return the names of classes that can be used to decode objects if their class is unavailable.
+ (NSArray *)classFallbacksForKeyedArchiver
An array of NSString objects that specify the names of classes in preferred order for unarchiving
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.
Developers who introduce a new class can use this method to provided 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.
NSKeyedArchiver.hOverridden by subclasses to substitute a new class during keyed unarchiving.
+ (Class)classForKeyedUnarchiver
The class to substitute for the receiver during keyed unarchiving.
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.
NSKeyedArchiver.hReturns a Boolean value that indicates whether the receiver conforms to a given protocol.
+ (BOOL)conformsToProtocol:(Protocol *)aProtocol
A protocol.
YES if the receiver conforms to aProtocol, otherwise NO.
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)]; |
NSObject.hReturns the receiver.
+ (id)copyWithZone:(NSZone *)zone
The receiver.
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.
NSObject.hReturns a string that represents the contents of the receiving class.
+ (NSString *)description
A string that represents the contents of the receiving class.
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.
description (NSObject protocol)NSObject.hInitializes the receiver before it’s used (before it receives its first message).
+ (void)initialize
The runtime sends initialize to each class in a program exactly one time just before the class, or any class that inherits from it, is sent its first message from within the program. (Thus the method may never be invoked if the class is not used.) The runtime sends the initialize message to classes in a thread-safe manner. Superclasses receive this message before their subclasses.
For example, if the first message your program sends is this:
[NSApplication new] |
the runtime system sends these three initialize messages:
[NSObject initialize]; |
[NSResponder initialize]; |
[NSApplication initialize]; |
because NSApplication is a subclass of NSResponder and NSResponder is a subclass of NSObject. All the initialize messages precede the new message.
If your program later begins to use the NSText class,
[NSText instancesRespondToSelector:someSelector] |
the runtime system invokes these additional initialize messages:
[NSView initialize]; |
[NSText initialize]; |
because NSText inherits from NSObject, NSResponder, and NSView. The instancesRespondToSelector: message is sent only after all these classes are initialized. Note that the initialize messages to NSObject and NSResponder aren’t repeated.
You implement initialize to provide class-specific initialization as needed. Since the runtime sends appropriate initialize messages automatically, you should typically not send initialize to super in your implementation.
If a particular class does not implement initialize, the initialize method of its superclass is invoked twice, once for the superclass and once for the non-implementing subclass. If you want to make sure that your class performs class-specific initializations only once, implement initialize as in the following example:
@implementation MyClass |
+ (void)initialize |
{ |
if ( self == [MyClass class] ) { |
/* put initialization code here */ |
} |
} |
Loading a subclasses of MyClass that does not implement its own initialize method will cause MyClass's implementation to be invoked. The test clause (if ( self == [MyClass class] )) ensures that the initialization code has no effect if initialize is invoked when a subclass is loaded.
initialize it 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.
NSObject.hLocates and returns the address of the implementation of the instance method identified by a given selector.
+ (IMP)instanceMethodForSelector:(SEL)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:.
See “Selectors” for a description of the SEL type.
The address of the implementation of the aSelector instance method.
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.
See “Selectors” for a description of the IMP type, and how to invoke the returned method implementation.
NSObject.hReturns an NSMethodSignature object that contains a description of the instance method identified by a given selector.
+ (NSMethodSignature *)instanceMethodSignatureForSelector:(SEL)aSelector
A selector that identifies the method for which to return the implementation address.
See “Selectors” for a description of the SEL type.
An NSMethodSignature object that contains a description of the instance method identified by aSelector, or nil if the method can’t be found.
NSObject.hReturns a Boolean value that indicates whether instances of the receiver are capable of responding to a given selector.
+ (BOOL)instancesRespondToSelector:(SEL)aSelector
A selector. See “Selectors” for a description of the SEL type.
YES if instances of the receiver are capable of responding to aSelector messages, otherwise NO.
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:.
NSObject.hReturns a Boolean value that indicates whether the receiving class is a subclass of, or identical to, a given class.
+ (BOOL)isSubclassOfClass:(Class)aClass
A class object.
YES if the receiving class is a subclass of—or identical to—aClass, otherwise NO.
NSObject.hInvoked whenever a class or category is added to the Objective-C runtime; implement this method to perform class-specific behavior upon loading.
+ (void)load
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.
On Mac OS X v10.5, the order of initialization is as follows:
All initializers in any framework you link to.
All +load methods in your image.
All C++ static initializers and C/C++ __attribute__(constructor) functions in your image.
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 +load method, you can therefore safely message other unrelated classes from the same image, but any +load methods on those classes may not have run yet.
NSObject.hReturns the receiver.
+ (id)mutableCopyWithZone:(NSZone *)zone
The memory zone in which to create the copy of the receiver.
The receiver.
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.
NSObject.hAllocates a new instance of the receiving class, sends it an init message, and returns the initialized object.
+ (id)new
A new instance of the receiver.
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.
Unlike alloc, new is sometimes re-implemented in subclasses to invoke a class-specific initialization method. If the init... method includes arguments, they’re typically reflected in a new... method as well. For example:
+ newMyClassWithTag:(int)tag data:(struct info *)data |
{ |
return [[self alloc] initWithTag:tag data:data]; |
} |
However, there’s little point in implementing a new... method if it’s simply a shorthand for alloc and init..., as shown above. Often new... methods will do more than just allocation and initialization. In some classes, they manage a set of instances, returning the one with the requested properties if it already exists, allocating and initializing a new instance only if necessary. For example:
+ newMyClassWithTag:(int)tag data:(struct info *)data |
{ |
MyClass *theInstance; |
if ( theInstance = findTheObjectWithTheTag(tag) ) |
return [theInstance retain]; |
return [[self alloc] initWithTag:tag data:data]; |
} |
Although it’s appropriate to define new new... methods in this way, the alloc and allocWithZone: methods should never be augmented to include initialization code.
If you are using managed memory (not garbage collection), this method retains the object before returning it. The returned object has a retain count of 1 and is not autoreleased. The invoker of this method is responsible for releasing the returned object, using either release or autorelease.
NSObject.hDynamically provides an implementation for a given selector for a class method.
+ (BOOL)resolveClassMethod:(SEL)name
The name of a selector to resolve.
YES if the method was found and added to the receiver, otherwise NO.
This method allows you to dynamically provide an implementation for a given selector. See resolveInstanceMethod: for further discussion.
NSObject.hDynamically provides an implementation for a given selector for an instance method.
+ (BOOL)resolveInstanceMethod:(SEL)name
The name of a selector to resolve.
YES if the method was found and added to the receiver, otherwise NO.
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]; |
} |
This method is called before the Objective-C forwarding mechanism (see Message Forwarding in Objective-C Runtime Programming Guide) 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.
NSObject.hSets the receiver's version number.
+ (void)setVersion:(NSInteger)aVersion
The version number for the receiver.
The version number is helpful when instances of the class are to be archived and reused later. The default version is 0.
The version number applies to NSArchiver/NSUnarchiver, but not to NSKeyedArchiver/NSKeyedUnarchiver. A keyed archiver does not encode class version numbers.
NSObject.hReturns the class object for the receiver’s superclass.
+ (Class)superclass
The class object for the receiver’s superclass.
+ classsuperclass (NSObject protocol)NSObject.hReturns the version number assigned to the class.
+ (NSInteger)version
The version number assigned to the class.
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.
The version number applies to NSArchiver/NSUnarchiver, but not to NSKeyedArchiver/NSKeyedUnarchiver. A keyed archiver does not encode class version numbers.
+ setVersion:versionForClassName: (NSCoder)NSObject.hOverridden by subclasses to substitute another object in place of the object that was decoded and subsequently received this message.
- (id)awakeAfterUsingCoder:(NSCoder *)aDecoder
The decoder used to decode the receiver.
The receiver, or another object to take the place of the object that was decoded and subsequently received this message.
This method can be used 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. To prevent the accidental use of the receiver after its replacement has been returned, you should invoke the receiver’s release method to release the object immediately.
This method is invoked by NSCoder. NSObject’s implementation simply returns self.
– classForCoder– replacementObjectForCoder:initWithCoder: (NSCoding protocol)NSObject.hOverridden by subclasses to substitute a class other than its own during coding.
- (Class)classForCoder
The class to substitute for the receiver's own class during coding.
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.
NSObject.hOverridden by subclasses to substitute a new class for instances during keyed archiving.
- (Class)classForKeyedArchiver
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.
NSKeyedArchiver.hReturns the object returned by copyWithZone:, where the zone is nil.
- (id)copy
The object returned by the NSCopying protocol method copyWithZone:, where the zone is nil.
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.
If you are using managed memory (not garbage collection), this method retains the new object before returning it. The invoker of the method, however, is responsible for releasing the returned object.
NSObject.hDeallocates the memory occupied by the receiver.
- (void)dealloc
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 never send a dealloc message directly. Instead, an object’s dealloc method is invoked indirectly through the release NSObject protocol method (if the release message results in the receiver's retain count becoming 0). See Memory Management Programming Guide for Cocoa for more details on the use of these methods.
Subclasses must implement their own versions of dealloc to allow the release of any additional memory consumed by the object—such as dynamically allocated storage for data or object instance variables owned by the deallocated object. After performing the class-specific deallocation, the subclass method should incorporate superclass versions of dealloc through a message to super:
- (void)dealloc { |
[companion release]; |
NSZoneFree(private, [self zone]) |
[super dealloc]; |
} |
Important: Note that when an application terminates, objects may not be sent a dealloc message since the process’s memory is automatically cleared on exit—it is more efficient simply to allow the operating system to clean up resources than to invoke all the memory management methods. For this and other reasons, you should not manage scarce resources in dealloc—see Object Ownership and Disposal in Memory Management Programming Guide for Cocoa for more details.
When garbage collection is enabled, the garbage collector sends finalize to the receiver instead of dealloc.
When garbage collection is enabled, this method is a no-op.
autorelease (NSObject protocol)release (NSObject protocol)– finalizeNSObject.hHandles messages the receiver doesn’t recognize.
- (void)doesNotRecognizeSelector:(SEL)aSelector
A selector that identifies a method not implemented or recognized by the receiver.
See “Selectors” for a description of the SEL type.
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.
NSObject.hThe garbage collector invokes this method on the receiver before disposing of the memory it uses.
- (void)finalize
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.
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.
NSObject.hOverridden by subclasses to forward messages to other objects.
- (void)forwardInvocation:(NSInvocation *)anInvocation
The invocation to forward.
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.
Important: To respond to methods that your object does not itself recognize, you must override methodSignatureForSelector: in addition to forwardInvocation:. The mechanism for forwarding messages uses information obtained from methodSignatureForSelector: to create the NSInvocation object to be forwarded. Your overriding method must provide an appropriate method signature for the given selector, either by preformulating one or by asking another object for one.
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 |
[self doesNotRecognizeSelector:aSelector]; |
} |
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.
NSObject.hImplemented by subclasses to initialize a new object (the receiver) immediately after memory for it has been allocated.
- (id)init
The initialized receiver.
An init message is generally 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.
Subclass implementations of this method should initialize and return the new object. If it can’t be initialized, they should release the object and return nil. In some cases, an init method might release the new object and return a substitute. Programs should therefore always use the object returned by init, and not necessarily the one returned by alloc or allocWithZone:, in subsequent code.
Every class must guarantee that the init method either returns a fully functional instance of the class or raises an exception. Subclasses should override the init method to add class-specific initialization code. Subclass versions of init need to incorporate the initialization code for the classes they inherit from, through a message to super:
- (id)init |
{ |
if ((self = [super init])) { |
/* class-specific initialization goes here */ |
} |
return self; |
} |
Note that the message to super precedes the initialization code added in the method. This sequencing ensures that initialization proceeds in the order of inheritance.
Subclasses often define init... methods with additional arguments to allow specific values to be set. The more arguments a method has, the more freedom it gives you to determine the character of initialized objects. Classes often have a set of init... methods, each with a different number of arguments. For example:
- (id)init; |
- (id)initWithTag:(int)tag; |
- (id)initWithTag:(int)tag data:(struct info *)data; |
The convention is that at least one of these methods, usually the one with the most arguments, includes a message to super to incorporate the initialization of classes higher up the hierarchy. This method is called the designated initializer for the class. The other init... methods defined in the class directly or indirectly invoke the designated initializer through messages to self. In this way, all init... methods are chained together. For example:
- (id)init |
{ |
return [self initWithTag:-1]; |
} |
- (id)initWithTag:(int)tag |
{ |
return [self initWithTag:tag data:NULL]; |
} |
- (id)initWithTag:(int)tag data:(struct info *)data |
{ |
if ((self = [super init. . .])) { |
/* class-specific initialization goes here */ |
} |
return self; |
} |
In this example, the initWithTag:data: method is the designated initializer for the class.
If a subclass does any initialization of its own, it must define its own designated initializer. This method should begin by sending a message to super to invoke the designated initializer of its superclass. Suppose, for example, that the three methods illustrated above are defined in the B class. The C class, a subclass of B, might have this designated initializer:
- (id)initWithTag:(int)tag data:(struct info *)data object:anObject |
{ |
if ((self = [super initWithTag:tag data:data])) { |
/* class-specific initialization goes here */ |
} |
return self; |
} |
If inherited init... methods are to successfully initialize instances of the subclass, they must all be made to (directly or indirectly) invoke the new designated initializer. To accomplish this, the subclass is obliged to cover (override) only the designated initializer of the superclass. For example, in addition to its designated initializer, the C class would also implement this method:
- (id)initWithTag:(int)tag data:(struct info *)data |
{ |
return [self initWithTag:tag data:data object:nil]; |
} |
This code ensures that all three methods inherited from the B class also work for instances of the C class.
Often the designated initializer of the subclass overrides the designated initializer of the superclass. If so, the subclass need only implement the one init... method.
These conventions maintain a direct chain of init... links and ensure that the new method and all inherited init... methods return usable, initialized objects. They also prevent the possibility of an infinite loop wherein a subclass method sends a message (to super) to perform a superclass method, which in turn sends a message (to self) to perform the subclass method.
This init method is the designated initializer for the NSObject class. Subclasses that do their own initialization should override it, as described above.
NSObject.hLocates and returns the address of the receiver’s implementation of a method so it can be called as a function.
- (IMP)methodForSelector:(SEL)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:.
The address of the receiver’s implementation of the aSelector.
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.
See “Selectors” for a description of the IMP and SEL types, and how to invoke the returned method implementation.
NSObject.hReturns an NSMethodSignature object that contains a description of the method identified by a given selector.
- (NSMethodSignature *)methodSignatureForSelector:(SEL)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.
See “Selectors” for a description of the SEL type.
An NSMethodSignature object that contains a description of the method identified by aSelector, or nil if the method can’t be found.
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.
NSObject.hReturns the object returned by mutableCopyWithZone: where the zone is nil.
- (id)mutableCopy
The object returned by the NSMutableCopying protocol method mutableCopyWithZone:, where the zone is nil.
This is a convenience method for classes that adopt the NSMutableCopying protocol. An exception is raised if there is no implementation for mutableCopyWithZone:.
If you are using managed memory (not garbage collection), this method retains the new object before returning it. The invoker of the method, however, is responsible for releasing the returned object.
NSObject.hInvokes a method of the receiver on the specified thread using the default mode.
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait
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.
See “Selectors” for a description of the SEL type.
The thread on which to execute aSelector.
The argument to pass to the method when it is invoked. Pass nil if the method does not take an argument.
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.
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.
This method retains the receiver and the arg parameter until after the selector is performed.
– performSelector:onThread:withObject:waitUntilDone:modes:– performSelectorInBackground:withObject:NSThread.hInvokes a method of the receiver on the specified thread using the specified modes.
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait modes:(NSArray *)array
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.
See “Selectors” for a description of the SEL type.
The thread on which to execute aSelector. This thread represents the target thread.
The argument to pass to the method when it is invoked. Pass nil if the method does not take an argument.
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.
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.
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.
This method retains the receiver and the arg parameter until after the selector is performed.
NSThread.hInvokes 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
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.
See “Selectors” for a description of the SEL type.
The argument to pass to the method when it is invoked. Pass nil if the method does not take an argument.
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.
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. To ensure that the selector is performed on the main thread, use the performSelectorOnMainThread:withObject:waitUntilDone: or performSelectorOnMainThread:withObject:waitUntilDone:modes: method instead. To cancel a queued message, use the cancelPreviousPerformRequestsWithTarget: or cancelPreviousPerformRequestsWithTarget:selector:object: method.
This method retains the receiver and the anArgument parameter until after the selector is performed.
+ cancelPreviousPerformRequestsWithTarget:selector:object:– performSelectorOnMainThread:withObject:waitUntilDone:– performSelectorOnMainThread:withObject:waitUntilDone:modes:– performSelector:onThread:withObject:waitUntilDone:modes:NSRunLoop.hInvokes 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
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.
See “Selectors” for a description of the SEL type.
The argument to pass to the method when it is invoked. Pass nil if the method does not take an argument.
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.
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.
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. To ensure that the selector is performed on the main thread, use the performSelectorOnMainThread:withObject:waitUntilDone: or performSelectorOnMainThread:withObject:waitUntilDone:modes: method instead. To cancel a queued message, use the cancelPreviousPerformRequestsWithTarget: or cancelPreviousPerformRequestsWithTarget:selector:object: method.
This method retains the receiver and the anArgument parameter until after the selector is performed.
– performSelector:withObject:afterDelay:– performSelectorOnMainThread:withObject:waitUntilDone:– performSelectorOnMainThread:withObject:waitUntilDone:modes:– performSelector:onThread:withObject:waitUntilDone:modes:addTimer:forMode: (NSRunLoop)invalidate (NSTimer)NSRunLoop.hInvokes a method of the receiver on a new background thread.
- (void)performSelectorInBackground:(SEL)aSelector withObject:(id)arg
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.
See “Selectors” for a description of the SEL type.
The argument to pass to the method when it is invoked. Pass nil if the method does not take an argument.
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.
This method retains the receiver and the arg parameter until after the selector is performed.
NSThread.hInvokes a method of the receiver on the main thread using the default mode.
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait
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.
See “Selectors” for a description of the SEL type.
The argument to pass to the method when it is invoked. Pass nil if the method does not take an argument.
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.
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 default 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 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.
This method retains the receiver and the arg parameter until after the selector is performed.
– performSelector:withObject:afterDelay:– performSelector:withObject:afterDelay:inModes:– performSelectorOnMainThread:withObject:waitUntilDone:modes:– performSelector:onThread:withObject:waitUntilDone:modes:NSThread.hInvokes 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
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.
See “Selectors” for a description of the SEL type.
The argument to pass to the method when it is invoked. Pass nil if the method does not take an argument.
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.
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.
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.
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.
This method retains the receiver and the arg parameter until after the selector is performed.
– performSelector:withObject:afterDelay:– performSelector:withObject:afterDelay:inModes:– performSelectorOnMainThread:withObject:waitUntilDone:– performSelector:onThread:withObject:waitUntilDone:modes:NSThread.hOverridden by subclasses to substitute another object for itself during encoding.
- (id)replacementObjectForCoder:(NSCoder *)aCoder
The coder encoding the receiver.
The object encode instead of the receiver (if different).
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.
NSObject.hOverridden by subclasses to substitute another object for itself during keyed archiving.
- (id)replacementObjectForKeyedArchiver:(NSKeyedArchiver *)archiver
A keyed archiver creating an archive.
The object encode instead of the receiver (if different).
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).
NSKeyedArchiver.hLast updated: 2009-08-28