Jump to content

Compiler Construction/Objective-C

From Wikibooks, open books for an open world

Objective-C

[edit | edit source]

Objects and fields

[edit | edit source]

In Objective-C, each class is a struct in C. That is,

@interface A
{
  int a, b, c
}

@end

would be implemented as like:

struct A {
  int a, b, c;
  .... // some runtime information
};

Thus, since each object in Objective-C, a pointer to a memory block in the heap. And so the way to access fields is the same as the way for members of struct. That is,

id obj = [A alloc];

The implication of this scheme is that while an object naturally fits to non-OOP C program, one disadvantage is that fields cannot be "shadowed." That is,

@interface A
{
  @private
  int a;
}
@end

@interface B : A
{
  @private
  int a;
}
@end

This would result in duplicate members error. This contrasts with the situation in Java.

Finally, since the selection of methods occurs at runtime (in contrast to the cases in Java or C++), methods are handled differently than fields.

Methods

[edit | edit source]

In Objective-C, the selection of methods occurs at runtime. Compilers may issue warnings about likely mistyped names because the compiler can know a set of selector names that are defined in the program. This, however, is not semantically necessary; any message can be sent to any object.

Semantically, the sender of a message checks if a given object responds to the message, and if not, try its super class, and if not again, its super and so on.

A complication may arise, for example, when there are two selectors with the differing return type. Consider the following case.

@interface A { }
- (float) func: (int) i
@end

@interface B { }
- (int) func: (int) i
@end

In this case, because the compiler cannot know to which method--(float) func or (int) func—an object would respond, it cannot generate code that sends a message, as returning a float value usually differs from doing an int value.