开发者

How to create an NSDictionary with two values per key from plist

开发者 https://www.devze.com 2023-01-08 04:43 出处:网络
I have a dependent UIPicker that loads the values into its two components from a plist.It\'s an NSDictionary with NSArrays of strings.The user selects a pair of components and the picker sends those t

I have a dependent UIPicker that loads the values into its two components from a plist. It's an NSDictionary with NSArrays of strings. The user selects a pair of components and the picker sends those two strings back to the delegate. What I really need is a constant that goes along with each individual choice. For example, first component is A, B, C and each choice has three subchoices A1, A2, A3, etc... User selects ChoiceA with ChoiceA3 and the picker return开发者_运维百科s the two strings fine, but I have a numeric constant that is associate with A-A3 and that is what I actually need for the math in my program.

Can I have two things associated with a particular key - a string AND a number? I guess what I want is a key-value-value pair (triplet)? It seems like using logic in my program to assign a value based on the key-value pair returned defeats the purpose of using a plist in the first place.


The ideal structure is actually to have a dictionary of dictionaries.

A = {
  A1 = 36;
  A2 = 42;
  A3 = 89;
};
B = {
  B1 = 64;
  ...

The plist is just a (collection of) serialization format. I don't see how it's defeated.


To store key-value-value, you have 2 choices.

(1) Create a new class.

@interface StringNumberPair : NSObject {
  NSString* strval;
  int intval;
}
@property(copy) NSString* strval;
@property(assign) int intval;
-(id)initWithString:(NSString*)strval_ integer:(int)intval_;
@end
...

[theDict setObject:[[[StringNumberPair alloc] initWithString:@"string"
                                                     integer:42] autorelease]
            forKey:@"key"];
  • Pro — Clear interface.
  • Cons — You need to write a lot of code.

(2) Make the value an array:

[theDict setObject:[NSArray arrayWithObjects:
                            @"string", [NSNumber numberWithInt:42], nil]
            forKey:@"key"];

or a dictionary:

[theDict setObject:[NSDictionary dictionaryWithObjectsAndKeys:
                      @"string",                   @"strval",
                      [NSNumber numberWithInt:42], @"intval",
                      nil]
            forKey:@"key"];
  • Pro — These are standard types to store structured values. It is easily serializable to a plist.
  • Cons — Arrays and dictionary are too flexible.


You said your value is an array of strings right?

So you can convert the numeric constant to string

[NSString stringWithFormat:@"%d"numericConstant]

and add it to the array.

Convert it back to int when you fetch it from dictionary

[stringConstant intValue]
0

精彩评论

暂无评论...
验证码 换一张
取 消