当前位置: 动力学知识库 > 问答 > 编程问答 >

class - Objective C: What does [ClassName self]; do?

问题描述:

I'm looking through the source code for the CocoaHTTPServer project, more specifically the HTTPServer.m file and I just don't understand this line:

connectionClass = [HTTPConnection self];

What does this do (is it documented anywhere)? How does it even compile? Should it not be

connectionClass = [HTTPConnection class];

网友答案:

In this context, - (id)self is a method defined on NSObject. It returns the receiver. For a Class it should obviously do the same as a call to the -(Class)class.

Class objects are thus full-fledged objects that can be dynamically typed, receive messages, and inherit methods from other classes. They’re special only in that they’re created by the compiler.

网友答案:

[Classname self] is equal to [Classname class] and returns a reference to the class object.

A little sample code illustrates this:

#import <Foundation/Foundation.h>

int main(int argc, char *argv[]) {
NSAutoreleasePool *p = [[NSAutoreleasePool alloc] init];

NSLog(@"Output 1: %@ address:%x",[NSString self], [NSString self]);
NSLog(@"Output 2: %@ address:%x",[NSString class], [NSString class]);

[p release];

}

Output:

2012-02-22 15:36:13.427 Untitled[1218:707] Output 1: NSString address:7b306a08
2012-02-22 15:36:13.428 Untitled[1218:707] Output 2: NSString address:7b306a08
网友答案:

[className self]; is same as [className class];
Returns the class object.
For example:

id object = [getSystemEventsAppDelegate self];
id object1 = [getSystemEventsAppDelegate class];  

网友答案:

In a very basic nutshell self is a reference to the current object, you pass that as a variable to (in this case) HTTPConnection, then assign the result of that method to the variable.

So if you look at HTTPConnection you'll be able to see how it uses that object reference and what it's going to return.

分享给朋友:
您可能感兴趣的文章:
随机阅读: