Added initWithObjectsAndKeys to CPDictionary From: Vladimir Pouzanov --- Foundation/CPDictionary.j | 66 +++++++++++++++++++++++++++++++++++++++++++++ 1 files changed, 66 insertions(+), 0 deletions(-) diff --git a/Foundation/CPDictionary.j b/Foundation/CPDictionary.j index 5935585..bd72048 100755 --- a/Foundation/CPDictionary.j +++ b/Foundation/CPDictionary.j @@ -124,6 +124,37 @@ } /*! + Creates and returns a dictionary constructed by a given pairs of keys and values. + @param firstObject first object value + @param ... key for the first object and ongoing value-key pairs for more objects. + @throws CPInvalidArgumentException if the number of objects and keys is different + @return the new CPDictionary + + Assuming that there's no object retaining in Cappuccino, you can create + dictionaries same way as with alloc and initWithObjectsAndKeys: +
var dict = [CPDictionary dictionaryWithObjectsAndKeys:
+    @"value1", @"key1",
+    @"value2", @"key2"];
+ + Note, that there's no final nil like in Objective-C/Cocoa. + + @see [CPDictionary initWithObjectsAndKeys:] +*/ ++ (id)dictionaryWithObjectsAndKeys:(id)firstObject, ... +{ + // XXX: duplicate implementation is bad, but so it's done in CPArray + // The arguments array contains self and _cmd, so the first object is at position 2. + var d = [self alloc]; + var arglist = [d, "initWithObjectsAndKeys:"]; + for(var i = 2; ivar dict = [[CPDictionary alloc] initWithObjectsAndKeys: + @"value1", @"key1", + @"value2", @"key2"]; + + Note, that there's no final nil like in Objective-C/Cocoa. +*/ +- (id)initWithObjectsAndKeys:(id)firstObject, ... +{ + // The arguments array contains self and _cmd, so the first object is at position 2. + var i = 2, + aValue, + aKey; + + self = [super init]; + + if (arguments.length % 2 != 0) + [CPException raise:CPInvalidArgumentException reason:"Key-value count is mismatched. ("+arguments.length+" arguments passed)"]; + + if (self) + { + for(; i < arguments.length && (aValue = arguments[i]) != nil && (aKey = arguments[i+1]); i+=2) + [self setObject:aValue forKey:aKey]; + } + + return self; +} + +/*! return a copy of the receiver (does not deep copy the objects contained in the dictionary). */ - (CPDictionary)copy