Accessor method idioms...
Accessor method idioms...
- Subject: Accessor method idioms...
- From: Mike Ferris <email@hidden>
- Date: Thu, 24 Mar 2005 08:15:00 -0800
I have been thinking about accessor methods recently and I wanted to
see if I could spark some discussion. Don't worry, I am not trying to
incite a "proper implementation of -foo/-setFoo:" debate. ;-)
Actually, what I have been considering is what the appropriate set of
public accessors is for an NSArray-valued key.
I know what all the KVC methods are. What bums me out about those is
the surface area it adds to an API if you use them as the public
accessors. What I have been gravitating towards is something like
what's below.
Has anyone else settled on this sort of thing? What I like it that the
API is small (only one more method than non-array accessors) and that I
do not have to basically duplicate the API os NSMutableArray, per-key
in my own object (although I still do so in the implementation to most
efficiently support -mutableArrayValueForKey:...)
Mike Ferris
// Public API
@interface Foo : NSObject {
NSMutableArray *_things;
}
- (NSArray *)things;
- (void)setThings:(NSArray *)newThings;
- (NSMutableArray *)mutableThings;
@end
// Implementation
@implementation Foo
- (NSArray *)things {
return [[_things retain] autorelease];
}
- (void)setThings:(NSArray *)newThings {
if (_things != newThings) {
NSMutableArray *mutThings = [self mutableThings];
[mutThings removeAllObjects];
if (newThings) {
[mutThings addObjectsFromArray:newThings];
}
}
}
- (NSMutableArray *)mutableThings {
return [self mutableArrayValueForKey:@"things"];
}
// Private support methods
- (unsigned)countOfThings {
return [_things count];
}
- (id)objectInThingsAtIndex:(unsigned)theIndex {
return [_things objectAtIndex:theIndex];
}
- (void)getThings:(id *)objArray range:(NSRange)range {
[_things getObjects:objArray range:range];
}
- (void)insertObject:(id)newObject inThingsAtIndex:(unsigned)theIndex {
[_things insertObject:newObject atIndex:theIndex];
}
- (void)removeObjectFromThingsAtIndex:(unsigned)theIndex {
[_things removeObjectAtIndex:theIndex];
}
-(void)replaceObjectInThingsAtIndex:(unsigned)theIndex
withObject:(id)newObject {
[_things replaceObjectAtIndex:(unsigned)theIndex
withObject:newObject];
}
@end
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden