Scoping of functions
Scoping of functions
- Subject: Scoping of functions
- From: Bill Bumgarner <email@hidden>
- Date: Wed, 29 May 2002 18:00:52 -0400
In short, a function (or variable) declared inside of an @implementation/@
end block will have the exact same scoping rules as it would if it were in
a straight C file. The @implementation block does not influence scoping
beyond the class to which a particular method's implementation will be
assigned.
Likewise...
static int foo;
@implementation MyClass
static int bar;
@end
... foo and bar are scoped identically in the above example.
ObjC is really just a very simple/small set of additions to ANSI-C. ObjC
tries hard not to modify the behavior of straight C. Historically, the
original implementation of ObjC in the early/mid '80s was a combination of
a preprocessor and a library that contained the runtime. That is,
Objective-C code would be parsed and turned into straight C code via the
preprocessor, then compiled as standard C code. (Not that that really
gives indication as to how the scoping might work...)
Another source of confusion: ObjC does *not* have class variables. As
long as you stick to a general rule of 'one class per .h or .m', then
static variables as shown above are, effectively, class variables. Write
class methods to get/set the variables, as desired.
Common idiom:
static MyThingamahover * defaultThingamahover = nil;
....
@implementation MyThingamahover
+ defaultThingamahover
{
if (! defaultThingamahover) {
defaultThingamahover = [self alloc];
[defaultThingamahover init];
}
return sharedInstance;
}
@end
The above implements the concept of a shared instance-- a singleton shared
across the app-- in the same fashion os NSNotificationCenter,
NSDefaultManager, NSApplication and others.
Exercise for the reader: It is a really good idea to separate the call to
+alloc from the call to -init....
b.bum
On Wednesday, May 29, 2002, at 05:39 PM, email@hidden
wrote:
void fnc(void) { ... }
....
@implementation Blah
....
void fnc2(void) { ... }
....
@end
Both cases are perfectly all right.
That's good to know. The Obj-C book doesn't really elaborate on this, so
I assumed that only class and instance methods were allowed in an
implementation. If you wanted to access the function from outside of the
class (such as call it from elsewhere), would being within the
@implementation/@end hide the function since it lies within the class'
namespace? What kind of scope does it have when inside the
implementation?
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.