开发者

basic question about structure

struct
{
int integer;
float real;
}
first_structure;

So we can refer to a member of the first_structure by writing

first_structure.integer = 7

If I write:

    struct two_numbers
    {
    int integer;
    float real;
    }
    first_structure;

then I can use the tag *two_numbers* to create a second structure like this:

struct two_numbers second_structure;

I also understand that typedef can be used to create synonyms.

But I am unable to understand the code below (from the page http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocObjectsClasses.html):

typedef struct objc_class *Class;
typedef struct objc_object {
    Class isa;
} *id;

Every object thus has an isa variable tha开发者_如何学Got tells it of what class it is an instance.

HOW can it tell???? Please guide me through the meaning of this code.

Thank you.


That's a shortcut to:

struct objc_object
{
    Class isa;
};
typedef struct objc_object * id

The id type is a pointer to an objc_object structure. So when using an id type, you will use the -> operator instead of ., since it's a pointer.

Note that the Class type is also a pointer to a structure. That's called an opaque type.

It basically means the compiler will be able to calculate the size, since we have only a pointer, but it won't know the implementation details.

That kind of pattern is used to hide the actual implementation of a structure. The type is defined in a header file, but the implementation is only defined in a source file.

For instance, in a header file:

typedef struct A_Struct * A;

That's valid, and it defines a type to a structure pointer, even if that structure is not known actually.

Then in a source file:

struct A
{
    int x;
    int y;
};

Here's the real implementation. Users will be able to create A typed objects, but won't be able to access the members, since they are known only in your source file. Users will pass you A typed objects, but you'll be cast them to a struct A, so you can access it members.

IE:

void foo( A someObject )
{
    struct A * a;

    a    = ( struct A * )someObject;
    a->x = 42;
}


You can tell because when an object is instantiated, the runtime sets the isa pointer to reflect the name of the class. Similar to how a "selector" in objective-c may be used - if you're not familiar, basically a selector is a name of a method. Behind the scenes it is just an NSString, but it doesn't have to be (alternate implementation The Cocotron uses an enumeration of integer type I believe).

Basically the runtime is able to know what object is being created and therefore can set the isa pointer. And introspection can work because if you compare what the object is against a 'Class' you're probably just comparing behind-the-scenes NSStrings.

I hope this addresses your concern, if not I can help clarify

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜