How to count the mutable array objects in iphone? - objective-c

I am fresher to iOS. In my application i have 3 mutable arrays with objects like
NSMutableArray *MuteItem = [NSMutableArray alloc]initWithObjects:#"a", #"b", #"b", #"c", #"c", #"c", nil]];
NSMutableArray *MuteQuantity = [NSMutableArray alloc]initWithObjects:#"1", #"1", #"1", #"1", #"1", #"1", nil]];
NSMutableArray *MutePrice = [NSMutableArray alloc]initWithObjects:#"4", #"3", #"3", #"6", #"6", #"6", nil]];
Now i need to print that 3 mutable arrays values with counting the same item's quantity and calculate the price also like objects
MuteItem = { a, b, c }
MuteQuantity = { 1, 2, 3 } // counting of same item's quantity like {1, 1+1, 1+1+1}
MutePrice = { 4, 6, 18 } // here addition of same item's prices like {4, 3+3, 6+6+6}
So anybody, would you please help me in this problem. Thanks in advance.

This code will do exactly as you requested, and will even handle any keys in MuteItem, and will generate three new arrays with the aggregate information from each of the three original arrays.
NSMutableArray* muteItem = [[NSMutableArray alloc] initWithObjects: #"a", #"b", #"b", #"c", #"c", #"c", nil];
NSMutableArray* muteQuantity = [[NSMutableArray alloc] initWithObjects: #"1", #"1", #"1", #"1", #"1", #"1", nil];
NSMutableArray* mutePrice = [[NSMutableArray alloc] initWithObjects: #"4", #"3", #"3", #"6", #"6", #"6", nil];
NSMutableArray* setItem = [NSMutableArray array];
NSMutableArray* setQuantity = [NSMutableArray array];
NSMutableArray* setPrice = [NSMutableArray array];
NSSet* itemSet = [NSSet setWithArray: muteItem];
for (NSString* key in itemSet) {
NSIndexSet* indices = [muteItem indexesOfObjectsPassingTest: ^BOOL(id obj, NSUInteger idx, BOOL *stop) {
return [obj isEqualToString: key];
}];
__block NSInteger totalQuantity = 0;
__block NSInteger totalPrice = 0;
[indices enumerateIndexesUsingBlock: ^void(NSUInteger idx, BOOL *stop) {
totalQuantity += [[muteQuantity objectAtIndex: idx] integerValue];
totalPrice += [[mutePrice objectAtIndex: idx] integerValue];
}];
[setItem addObject: key];
[setQuantity addObject: [NSNumber numberWithInteger: totalQuantity]];
[setPrice addObject: [NSNumber numberWithInteger: totalPrice]];
}
NOTE: This code assumes you are using ARC. Also, in your original code you forgot to nil terminate your array constructors.
EDIT: I notice that your prices are integers, you may want to change them to floats if your currency uses decimal fractions. This would require changing the definition of totalPrice to float and you would want to change the end of the totalPrice += line from integerValue to floatValue.
EDIT2: Renamed all variables that started with a capital letter as this violates standard naming convention. Only class names should begin with a capital letter, variables should always begin with lowercase, or an _ for instance variables. :)

Related

Deleting Set of Indexs from NSMutableArray Efficiently

i have a set of Index setOFIndex = {0,1,3,4}.
now i want to remove this set of index from an NSMutableArray ?
what is the efficient method to do that ?
i have checked for any library method , but not able to find any.
i cant use removeObjectAtIndex directly as at each deletion array will be shifted by one.
NSMutableArray *array = [NSMutableArray arrayWithObjects: #"one", #"a", #"two", #"b", #"three", #"four", nil];
NSMutableIndexSet *indexes = [NSMutableIndexSet indexSetWithIndex:1];
[indexes addIndex:3];
[array removeObjectsAtIndexes:indexes];
NSLog(#"array: %#", array);
// Output: array: (one, two, three, four)
read the documentation
You should use NSMUTABleArray's method removeObjectsAtIndexes:
This is the code from documentation
NSMutableArray *array = [NSMutableArray arrayWithObjects: #"one", #"a", #"two", #"b", #"three", #"four", nil];
NSMutableIndexSet *indexes = [NSMutableIndexSet indexSetWithIndex:1];
[indexes addIndex:3];
[array removeObjectsAtIndexes:indexes];
NSLog(#"array: %#", array);
I simply don't understand why people don't read documentation.
Why don't you use
– removeObjectsInArray:
Convert your Indexset to array and then use above method.
EDIT:
Very straight forward example from documentation.
NSMutableArray *array = [NSMutableArray arrayWithObjects: #"one", #"a", #"two", #"b", #"three", #"four", nil];
NSMutableIndexSet *indexes = [NSMutableIndexSet indexSetWithIndex:1];
[indexes addIndex:3];
[array removeObjectsAtIndexes:indexes];
NSLog(#"array: %#", array);

Is there a more elegant way of finding unique NSDictionary keys within an NSArray?

Aim: To obtain an NSArray containing unique keys for given NSDictionary(s) using elegant code
Example Code with Current Working Solution:
NSArray *data = [[NSArray alloc] initWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:1], #"a", [NSNumber numberWithInt:2], #"b", nil],
[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:3], #"b", [NSNumber numberWithInt:4], #"c", nil],
[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:5], #"a", [NSNumber numberWithInt:6], #"c", nil],
[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:7], #"b", [NSNumber numberWithInt:8], #"a", nil],
[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:8], #"c", [NSNumber numberWithInt:9], #"b", nil],
nil];
// create an NSArray of all the dictionary keys within the NSArray *data
NSMutableSet *setKeys = [[NSMutableSet alloc] init];
for (int i=0; i<[data count]; i++) {
[setKeys addObjectsFromArray:[[data objectAtIndex:i] allKeys]];
}
NSArray *arrayKeys = [setKeys allObjects];
NSLog(#"arrayKeys: %#", arrayKeys);
Which returns the desired array of keys:
2012-06-11 16:52:57.351 test.kvc[6497:403] arrayKeys: (
a,
b,
c
)
Question: Is there a more elegant way of approaching this? Surely there must be some KVC approach that can get all the keys without having to iterate through the array? I've been looking at Apple Developer Documentation and can't see a solution. Any ideas? (looking at purely elegance of code rather than performance).
Normally you could use KVC by doing something like this:
NSArray *uniqueKeys = [data valueForKeyPath:#"#distinctUnionOfArrays.allKeys";
However NSDictionary overrides the valueForKey: selector which is used by the KVC internals, so this will not work correctly.
The documentation for NSDictionary's valueForKey: method tells us that:
If key does not start with “#”, invokes objectForKey:. If key does start with “#”, strips the “#” and invokes [super valueForKey:] with the rest of the key.
So we just insert an # before allKeys:
NSArray *uniqueKeys = [data valueForKeyPath:#"#distinctUnionOfArrays.#allKeys"];
And we get what we want:
(lldb) po [data valueForKeyPath:#"#distinctUnionOfArrays.#allKeys"]
(id) $14 = 0x07bb2fc0 <__NSArrayI 0x7bb2fc0>(
c,
a,
b
)
This is less ugly, and possibly marginally faster, I suppose:
NSMutableSet *setKeys = [[NSMutableSet alloc] init];
for (NSDictionary* dict in data) {
for (id key in [dict keyEnumerator]) {
[setKeys addObject:key];
}
}
But you're not doing a particularly common operation, so I wouldn't expect to find some incredibly elegant method. If that's what you want, go learn Haskell.
You could try this:
NSMutableSet *setKeys = [[NSMutableSet alloc] init];
for(NSDictionary *dict in data) {
[setKeys addObjectsFromArray:[dict allKeys]];
}
NSArray *arrayKeys = [setKeys allObjects];
If you prefer blocks you could use this:
[data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[setKeys addObjectsFromArray:[obj allKeys]];
}];

Sort NSMutableDictionary based on contents in NSMutable array

I have a array NSMutableArray with Values say
10, 2, 13, 4.
Also there is NSMutableDictionary with values say
(10, a), (20, b), (13, c), (2, d), (33, e)
I want to sort values in NSMutableDictionary in a way that result of dict should be (10, a), (2, d), (13, c)
I wrote for you function. Hope, it will help you:
- (void)removeUnnedful
{
NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
#"a", [NSNumber numberWithInt:10],
#"b", [NSNumber numberWithInt:20],
#"c", [NSNumber numberWithInt:13],
#"d", [NSNumber numberWithInt:2 ],
#"e", [NSNumber numberWithInt:33],
nil];
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:
[NSNumber numberWithInt:10],
[NSNumber numberWithInt:2 ],
[NSNumber numberWithInt:13],
[NSNumber numberWithInt:14], nil];
NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
for (NSNumber *key in [dict allKeys])
{
NSLog(#"%#", key);
if ([array containsObject:key])
{
[newDict setObject:[dict objectForKey:key] forKey:key];
}
}
for (NSNumber *key in [newDict allKeys])
NSLog(#"key: %#, value: %#", key, [newDict objectForKey:key]);
[dict release];
[array release];
}
Sort order of keys and values in an instance of NSDictionary is not defined. (see [NSDictionary allKeys])
As you already have an array of ordered keys, you can simply iterate over that and access the dictionary value for that key:
NSMutableArray* sortedArray = [NSMutableArray arrayWithObjects:#"10", #"2", #"13", #"4", nil];
NSDictionary* dictionary = [NSDictionary dictionaryWithObjectsAndKeys:#"a", #"10", #"b", #"20", #"c", #"13", #"d", #"2", #"e", #"33" , nil];
NSMutableDictionary* filteredDictionary = [NSMutableDictionary dictionary];
for(id key in sortedArray)
{
id value = [dictionary objectForKey:key];
if(value != nil)
{
[filteredDictionary setObject:[dictionary objectForKey:key] forKey:key];
}
}
NSLog(#"%#", filteredDictionary);
Note that the default implementation of [NSDictionary description] sorts the output ascending per key (for keys of type NSString), but this is just a representation - NSDictionaries have no defined sort order so you shouldn't rely on the sorting of allKeys and allValues

arrayByAddingObjectsFromArray?

I am not sure what I am doing wrong here? I have tried various combinations to try and copy an array into variable mmm. I am trying to learn how to create a 2D array and then run a loop to place init_array into 10 columns.
// NSMutableArray *mmm = [NSMutableArray arrayWithCapacity: 20];
NSMutableArray *kkk = [NSMutableArray arrayWithObjects: #"a", #"b", #"cat", #"dog", nil];
NSMutableArray *mmm; //= [NSMutableArray arrayWithObjects: #"1", #"2", #"3", #"4", nil];
[mmm arrayByAddingObjectsFromArray:kkk];
NSLog(#"Working: %#",[mmm objectAtIndex:3]);
thanks...
so this works from the given answer:
NSMutableArray *mmm = [NSMutableArray arrayWithCapacity: 20];
NSMutableArray *kkk = [NSMutableArray arrayWithObjects: #"a", #"b", #"cat", #"dog", nil];
[mmm addObjectsFromArray:kkk];
NSLog(#"Working: %#",[mmm objectAtIndex:3]);
arrayByAddingObjectsFromArray: returns a new (autoreleased) NSArray object. What you want is addObjectsFromArray:.
arrayByAddingObjectsFromArray: returns a new NSArray that includes the objects in the receiver followed by the objects in the argument. The code you posted there, with mmm unset, will probably just crash since mmm doesn't point to an NSArray object. If you had assigned an array to mmm, then it would return (#"1", #"2", #"3", #"4", #"a", #"b", #"cat", #"dog") — but you don't assign the result to any variable, so it just goes nowhere. You'd have to do something like NSArray *yetAnotherArray = [mmm arrayByAddingObjectsFromArray:kkk].
If you have an NSMutableArray and you want to add objects from another array, use addObjectsFromArray:.

Join an Array in Objective-C

I'm looking for a method of turning a NSMutableArray into a string. Is there anything on a par with this Ruby array method?
>> array1 = [1, 2, 3]
>> array1.join(',')
=> "1,2,3"
Cheers!
NSArray *array1 = [NSArray arrayWithObjects:#"1", #"2", #"3", nil];
NSString *joinedString = [array1 componentsJoinedByString:#","];
componentsJoinedByString: will join the components in the array by the specified string and return a string representation of the array.
The method you are looking for is componentsJoinedByString.
NSArray *a = [NSArray arrayWithObjects:#"1", #"2", #"3", nil];//returns a pointer to NSArray
NSString *b = [a componentsJoinedByString:#","];//returns a pointer to NSString
NSLog(#"%#", b); // Will output 1,2,3
NSArray class reference:
NSArray *pathArray = [NSArray arrayWithObjects:#"here",
#"be", #"dragons", nil];
NSLog(#"%#",
[pathArray componentsJoinedByString:#" "]);