views:

48

answers:

4

in objc.h , there is definition for Class

typedef struct objc_class *Class;

typedef struct objc_object {

  Class isa;
} *id;

Case : use Class in NSObject :

/*************** Basic protocols  ***************/

@protocol NSObject

- (BOOL)isEqual:(id)object;
- (NSUInteger)hash;

- (Class)superclass;
- (Class)class;
- (id)self;

Hard to understand, so Class is just structure, not real class like NSObject etc.

What is the real purpose of Class ?

A: 

I think you're on the wrong way.

the header file should loook like this:

#import <Foundation/NSObject.h>

@interface Fraction: NSObject {
    int numerator;
}

-(void) print;
@end

And the implementation (.m file) like this

#import "Fraction.h"
#import <stdio.h>

@implementation Fraction
-(void) print {
    printf( "%i", numerator );
}
@end

source

regards

ReaperXmac
I'm not sure you read the question correctly - the poster wants to know the purpose of Class.
Frank Shearar
A: 

In Objective-C, classes are "first-class objects". They are essential in runtime type checking, e.g. to check if an object is a string you can use

[obj isKindOfClass:[NSString class]];

-isKindOfClass: needs to accept an Objective-C class as a parameter, and Class is a representation of it.

(You seldom need to care the type definitions in objc.h unless you need to manipulate the Objective-C runtime below the C API level. )

KennyTM
A: 

Class lets the Objective-C runtime system know where to look for method tables (and instance variables etc.). In particular, when you write

[self foo: bar];

the runtime system calls

objc_msgSend(self, @selector(foo:), bar);

and then it uses self's type to find the right Class to find the appropriate method table to find the implementation corresponding to the foo: message. And then run it.

Frank Shearar
A: 

All of the dynamic behaviors of the Objective-C runtime are available because of the Class class. It's not a class that you will ever subclass or implement. The runtime fills in metadata about your class that can be accessed for introspection or modification.

Languages such as C++ and even Java have very limited support for this sort of thing. Objective-C is closer to the Ruby or Python scripting languages in this regard. You can actually replace instance methods in existing classes with your own implementation at run-time and affect the class in other ways that most compiled languages just can't touch.

Paul