enum and NSDictionary to define list of valid elements in Cocoa
I try to understand how to define a list of valid elements for a class:
Let's say i have a class People
and i need to accept only 3 strings as possible valid names
@"Luke"
,@"Paul"
,@"Mark"
.
I thought to use a combination of enum and NSDictionary this way (but i'm obviously not sure about the correctness of this method):
//INTERFACE*********************
typedef enum {
Luke,Paul,Mark
}ValidName;
@interface Person : NSObject{
// some code
}
@end
//IMPLEMENTATION*******************
@interface Person(private){
NSMutableDictionary *_validNamesDict;
}
@end
@interface Person:NSObject
- (id)init
{
self = [super init];
if (self) {
_validName开发者_Go百科sDict = [[NSMutableDictionary alloc] init];
[_validNamesDict setObject: @"Luke" forKey:[NSNumber numberWithInt: Luke]];
[_validNamesDict setObject: @"Paul" forKey:[NSNumber numberWithInt: Paul]];
[_validNamesDict setObject: @"Mark" forKey:[NSNumber numberWithInt: Mark]];
}
return self;
}
//Some code ....
Now in the rest of the class i refer to this name with:
[_validNameDict objecWithKey:[NSNumber numberWithInt: Luke]];
I'm pretty sure this is not the best method. Could you suggest me a valid way to manage this situation ? I read something about the use of extern keyword and definition to static variable into class... is it maybe a better method?
I think what you want here is a set, not a map--that is, an NSSet
, not an NSDictionary
.
Let's say you have the set validNames
and you want to determine if the name n
is in the set. Once your set is initialized, just do the following:
BOOL nameIsValid = [validNames containsObject:n];
精彩评论