sorting array and objetct - objective-c

How can I order these values ​​in the array in reverse order?
_gradientArrayToWhite = [[NSArray alloc] initWithObjects:#"1", #"2", #"3", #"4", #"5", #"6", #"7", #"8", #"9", #"10", nil];

Using one of the sorting methods of NSArray
NSArray * sorted = [_gradientArrayToWhite sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return [obj1 integerValue] < [obj2 integerValue];
}];

NSArray *arr = [NSArray arrayWithObjects:[NSNumber numberWithInt:1],[NSNumber numberWithInt:2],[NSNumber numberWithInt:3],[NSNumber numberWithInt:4],[NSNumber numberWithInt:5],[NSNumber numberWithInt:6],[NSNumber numberWithInt:7],[NSNumber numberWithInt:8],[NSNumber numberWithInt:9],[NSNumber numberWithInt:10], nil];
Here You can use your array directly also like this
NSArray *arr1 = [[NSArray alloc] initWithObjects:#"1", #"2", #"3", #"4", #"5", #"6", #"7", #"8", #"9", #"10", nil];
NSArray *revArr = [[arr reverseObjectEnumerator] allObjects];
Result = <__NSArrayM 0x71348e0>(
10,
9,
8,
7,
6,
5,
4,
3,
2,
1
)

Related

Sorting an NSArray that contains int with particular int

I have some data like this :
1, 5, 2, 9, 7, 6, 3, 8, 0, 4
but I actually want this:
5, 6, 7, 8, 9
only start to 5 .
and I use this:
NSArray *ary = #[ #"1", #"5", #"2", #"9", #"7", #"6", #"3", #"8", #"0", #"4" ];
NSArray *myArray = [ary sortedArrayUsingDescriptors:
#[[NSSortDescriptor sortDescriptorWithKey:#"doubleValue" ascending:YES]]];
NSString *numberExpr =#"^[5-9]";
NSArray *ary = #[ #"1", #"5", #"2", #"9", #"7", #"6", #"3", #"8", #"0", #"4" ];
NSArray *myArray= [ary filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"self MATCHES %#",numberExpr]];
This solution treats the contents as numeric, as suggested by the question's sample code.
double startingValue = 5;
NSArray *ary = #[ #"1", #"5", #"2", #"9", #"7", #"6", #"3", #"8", #"0", #"4" ];
NSArray *myArray= [ary filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"self.doubleValue >= %#", #(startingValue)]];
myArray = [myArray sortedArrayUsingDescriptors:
#[[NSSortDescriptor sortDescriptorWithKey:#"doubleValue" ascending:YES]]];

How to count the mutable array objects in iphone?

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. :)

Get NSArray of NSDictionary keys sorted by Value then Key

Say I have a dictionary with keys (words) and values (scores) as follows:
GOD 8
DONG 16
DOG 8
XI 21
I would like to create an NSArray of dictionary keys (words) that is sorted first by score then alphabetically. From the example above this would be:
XI
DONG
DOG
GOD
What's the best way to achieve this?
I would use and NSArray of NSDictionaries and then implement it using NSSortDescriptors:
NSSortDescriptor *sdScore = [NSSortDescriptor alloc] initWithKey:#"SCORE" ascending:NO];
NSSortDescriptor *sdName = [NSSortDescriptor alloc] initWithKey:#"NAME" ascending:YES];
NSArray *sortedArrayOfDic = [unsortedArrayOfDic sortedArrayUsingDescriptors:[NSArray arrayWithObjects: sdScore, sdName, nil]];
Carlos' answer is the correct one I'm just posting the full code I ended up with just in case anyone is interested:
NSDictionary *dataSourceDict = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:8], #"GOD",
[NSNumber numberWithInt:16], #"DONG",
[NSNumber numberWithInt:8], #"DOG",
[NSNumber numberWithInt:21], #"XI", nil];
NSSortDescriptor *scoreSort = [NSSortDescriptor sortDescriptorWithKey:#"SCORE" ascending:NO];
NSSortDescriptor *wordSort = [NSSortDescriptor sortDescriptorWithKey:#"WORD" ascending:YES];
NSArray *sorts = [NSArray arrayWithObjects:scoreSort, wordSort, nil];
NSMutableArray *unsortedArrayOfDict = [NSMutableArray array];
for (NSString *word in dataSourceDict)
{
NSString *score = [dataSourceDict objectForKey:word];
[unsortedArrayOfDict addObject: [NSDictionary dictionaryWithObjectsAndKeys:word, #"WORD", score, #"SCORE", nil]];
}
NSArray *sortedArrayOfDict = [unsortedArrayOfDict sortedArrayUsingDescriptors:sorts];
NSDictionary *sortedDict = [sortedArrayOfDict valueForKeyPath:#"WORD"];
NSLog(#"%#", sortedDict);
Related: NSDictionary split into two arrays (objects and keys) and then sorted both by the objects array (or a similar solution)
I couldn't test this because i'm not on a Mac (sorry if I misspelled something), but:
NSDictionary *dic1 = [NSDictionary dictionaryWithObjectsAndKeys:#"GOD", #"WORD", [NSNumber numberWithInt:8], #"SCORE", nil];
NSDictionary *dic2 = [NSDictionary dictionaryWithObjectsAndKeys:#"DONG", #"WORD", [NSNumber numberWithInt:16], #"SCORE", nil];
NSDictionary *dic3 = [NSDictionary dictionaryWithObjectsAndKeys:#"DOG", #"WORD", [NSNumber numberWithInt:8], #"SCORE", nil];
NSDictionary *dic4 = [NSDictionary dictionaryWithObjectsAndKeys:#"XI", #"WORD", [NSNumber numberWithInt:21], #"SCORE", nil];
NSSortDescriptor *scoreSort = [NSSortDescriptor sortDescriptorWithKey:#"SCORE" ascending:NO];
NSSortDescriptor *wordSort = [NSSortDescriptor sortDescriptorWithKey:#"WORD" ascending:YES];
NSArray *sortedArrayOfDic = [[NSArray arrayWithObjects:dic1, dic2, dic3, dic4, nil] sortedArrayUsingDescriptors:[NSArray arrayWithObjects:scoreSort, wordSort, nil]];
NSLog(#"%#", [sortedArrayOfDict valueForKeyPath:#"WORD"]);
This would do the same but a bit reduced and avoiding an iteration.

NSMutableDictionary not getting expected output.

Its only outputting one set for NSMutableDictionary not both. I want to create an JSON request using NSMutableDictionary (JSONRepresentation).
// My code
NSArray *keysEndpoint = [NSArray arrayWithObjects:#"ID", #"Name", #"EndpointType", nil];
NSArray *objectEndpoint = [NSArray arrayWithObjects:#"622", #"Brand", #"0", nil];
NSArray *keysEndpoint1 = [NSArray arrayWithObjects:#"ID", #"Name", #"EndpointType", nil];
NSArray *objectEndpoint1 = [NSArray arrayWithObjects:#"595", #"CK-05052011", #"1", nil];
NSMutableArray *keys1 = [[NSMutableArray alloc] initWithCapacity:0];
NSMutableArray *objects1 = [[NSMutableArray alloc] initWithCapacity:0];
[keys1 addObjectsFromArray:keysEndpoint];
[keys1 addObjectsFromArray:keysEndpoint1];
NSLog(#"Key Dic: %#", keys1);
[objects1 addObjectsFromArray:objectEndpoint];
[objects1 addObjectsFromArray:objectEndpoint1];
NSLog(#"Obje Dic: %#", objects1);
NSMutableDictionary *testMut = [NSMutableDictionary dictionaryWithObjects:objects1 forKeys:keys1];
NSLog(#"Test Dic: %#", testMut);
Output is am getting is this:
Test Dic: {
EndpointType = 1;
ID = 595;
Name = "CK-05052011";
}
Expexted output i want is :
Test Dic: {
EndpointType = 1;
ID = 595;
Name = "CK-05052011";
}
{
EndpointType = 0;
ID = 622;
Name = "Brand";
}
For a dictionary, adding the same keys twice will override the first set of keys. You should have a NSMutableArray of NSMutableDictionary
NSArray *keysEndpoint = [NSArray arrayWithObjects:#"ID", #"Name", #"EndpointType", nil];
NSArray *objectEndpoint = [NSArray arrayWithObjects:#"622", #"Brand", #"0", nil];
NSArray *keysEndpoint1 = [NSArray arrayWithObjects:#"ID", #"Name", #"EndpointType", nil];
NSArray *objectEndpoint1 = [NSArray arrayWithObjects:#"595", #"CK-05052011", #"1", nil];
NSMutableDictionary *testMut = [NSMutableDictionary dictionaryWithObjects:objectsEndpoint forKeys:keysEndpoint];
NSMutableDictionary *testMut1 = [NSMutableDictionary dictionaryWithObjects:objectsEndpoint1 forKeys:keysEndpoint1];
NSMutableArray * dictArray = [NSMutableArray arrayWithObjects:testMut,testMut1,nil];
NSLog(#"Test DictArray: %#", dictArray);

NSDictionary initialization results in "EXC_BAD_ACCESS"

I can not figure out why this code is bad. I thought it was ok to use static strings in dictionaryWithObjectsAndKeys however it fails at runtime with a EXC_BAD_ACCESS. I used the debugger to identify that it is in fact failing at the definition line. It never outputs "Made it here".
- (NSString *)polyName:(NSUInteger)vertices {
NSLog(#"looking for polyName with %d vertices.", vertices);
NSDictionary *polNameDict = [NSDictionary dictionaryWithObjectsAndKeys:
#"triangle", #"3",
#"square", #"4",
#"pentagon","5",
#"Hexagon", #"6",
#"Heptagon", #"7",
#"Octagon", #"8",
#"Nonagon", #"9",
#"Decagon", #"10",
#"Hendecagon", #"11",
#"Dodecagon", #"12",
nil];
NSLog(#"Made it here");
NSString *key = [NSString stringWithFormat: #"%d", vertices];
NSString *polName = [polNameDict objectForKey:key];
return (polName);
// Memory management: No need to release polNameDict, key, polName because they use
// convenience functions
}
The problem is here:
#"pentagon","5"
It expects an object (NSString) but instead there's a regular string.
Change it to:
#"pentagon", #"5"
What line does the EXC_BAD_ACCESS occur on? Utilize breakpoints and let us know.
For now, if I were you, I'd do something like this:
NSDictionary *polNameDict = [[NSDictionary alloc] initWithObjectsAndKeys:
#"triangle", #"3",
#"square", #"4",
#"pentagon",#"5",
#"Hexagon", #"6",
#"Heptagon", #"7",
#"Octagon", #"8",
#"Nonagon", #"9",
#"Decagon", #"10",
#"Hendecagon", #"11",
#"Dodecagon", #"12",
nil];
instead of how you have it now.