Re: private methods and variables
Re: private methods and variables
- Subject: Re: private methods and variables
- From: Bill Bumgarner <email@hidden>
- Date: Wed, 30 Jul 2008 11:23:46 -0700
On Jul 30, 2008, at 2:26 AM, Torsten Curdt wrote:
For Cocoa, functionality that is supported is made available
through public headers. Functionality that is internal to Cocoa is
encapsulated in private headers that declare said private
interfaces through a combination of categories, class extensions
and full-on class declarations.
Any pointers on how this is done?
Sure. Coding in a Compose Window Never Compiles -- you have been
warned.
Foo.h
-----
@class FooPrivateStuff;
@interface Foo : NSObject
{
FooPrivateStuff *privateStuff;
}
... public API here ...
@end
Foo_Private.h
-------------
@interface FooPrivateStuff:NSObject
{
@protected
... ivars declared here ...
}
@end
@implementation FooPrivateStuff
... you can either decide to manage the ivars in this class OR you
could simply treat this as a structure and access ivars through ->,
see below ...
If you want to the ivars to be fully managed by this private class,
then I would suggest implementing all of the ivars as non-atomic
properties and synthesized accessors. Don't forget your -dealloc in
this case.
Personally, I would go with properties as it allows Foo to use KVO to
handle change propagation in its internal private state.
@end
@interface Foo() // this is not a category -- a class extension --
thus all API declared here must be implemented in class
.... private API here
@end
Foo.m
-----
#import "Foo.h"
#import "Foo_Private.h"
@implementation Foo
- init {
... standard -init dance ...
privateStuff = [FooPrivateStuff new];
// if FooPrivateStuff is just being used as a structure
privateStuff->bob = [Bob new];
privateStuff->count = 10;
// if FooPrivateStuff declared everything as @property
privateStuff.bob = [Bob new];
privateStuff.count = 10;
}
// if not using GC, you'll need this... of course, not using GC is
generally a waste of time.
- dealloc {
[privateStuff->bob release]; // structure
privateStuff.bob = nil; // @property
[super dealloc];
}
----
So, why use a class and not a structure?
First, the garbage collector will precisely scan instances -- only
scanning slots that have object references -- this is more efficient
and avoids false references. Secondly, it makes the code easy to
refactor and enables the use of higher level mechanisms to manage the
private stuff -- KVO, KVC, etc... Finally, classes take care of
allocating enough space for their instance variables across all
architectures.
b.bum
Attachment:
smime.p7s
Description: S/MIME cryptographic signature
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden