I have NSMutableDictionary with Integers as Key and NSString as Values for example:
Key -- Value
1 -- B
2 -- C
3 -- A
Now i want to Sort NSMutableDictionary alphabetically using values. So i want my dictionary to be like : Key(3,1,2)->Value(A,B,C). How can i perform this?
From Apple docs:
https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Collections/Articles/Dictionaries.html#//apple_ref/doc/uid/20000134-SW4
Sorting dictionary keys by value:
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:63], #"Mathematics",
[NSNumber numberWithInt:72], #"English",
[NSNumber numberWithInt:55], #"History",
[NSNumber numberWithInt:49], #"Geography",
nil];
NSArray *sortedKeysArray =
[dict keysSortedByValueUsingSelector:#selector(compare:)];
// sortedKeysArray contains: Geography, History, Mathematics, English
Blocks ease custom sorting of dictionaries:
NSArray *blockSortedKeys = [dict keysSortedByValueUsingComparator: ^(id obj1, id obj2) {
if ([obj1 integerValue] > [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedDescending;
}
if ([obj1 integerValue] < [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}];
try this logic
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:#"B",#"B",#"A",#"A",#"C",#"C", nil];
NSMutableArray *sortedArray = [NSMutableArray arrayWithArray:[dict allKeys]];
[sortedArray sortUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
for (NSString *key in sortedArray) {
NSLog(#"%#",[dict objectForKey:key]);
}
Related
I want to change the Dictionary's all value to String, how to do with it?
Such as:
{ #"a":"a",
#"b":2,
#"c":{
#"c1":3,
#"c2":4
}
}
I want convert to :
{ #"a":"a",
#"b":"2",
#"c":{
#"c1":"3",
#"c2":"4"
}
}
How to do with it? I think all the day.
If I use below method to traverse the dictionary values:
NSArray *valueList = [dictionary allValues];
for (NSString * value in valueList) {
// change the value to String
}
If the value is a dictionary, how about it?
So, someone can help with that?
You could do this with a recursive method, it changes all NSNumber values to NSString and calls itself for nested dictionaries. Since a dictionary cannot be mutated while being enumerated a new dictionary is created and populated:
- (void)changeValuesOf:(NSDictionary *)dictionary result:(NSMutableDictionary *)result
{
for (NSString *key in dictionary) {
id value = dictionary[key];
if ([value isKindOfClass: [NSDictionary class]]) {
NSMutableDictionary * subDict = [NSMutableDictionary dictionary];
result[key] = subDict;
[self changeValuesOf:value result:subDict];
} else if ([value isKindOfClass: [NSNumber class]]) {
result[key] = [NSString stringWithFormat:#"%#", value];
} else {
result[key] = value;
}
}
}
NSDictionary *dictionary = #{#"a": #"a", # "b":#2, #"c": #{#"c1": #3, #"c2":#4 }};
NSMutableDictionary *result = [NSMutableDictionary dictionary];
[self changeValuesOf:dictionary result:result];
NSLog(#"%#", result);
You can create category for a dictionary and add method some like stringValueForKey:.
The realisation can be something like this:
- (NSString)stringValueForKey:(NSString*)key
{
id value = self[key];
if( [value respondsToSelector:#selector(stringValue)])
return [value performSelector:#selector(stringValue)]
return nil;
}
I have two array let's say
NSArray *array1=#[ #{#"key1":#"A",#"key2":#"AA"},#{#"key1":#"C",#"key2":#"CC"},#{#"key1":#"E",#"key2":#"EE"},#{#"key1":#"G",#"key2":#"GG"}];
NSArray *array2=#[ #{#"key1":#"A",#"key2":#"AAA"},#{#"key1":#"Z",#"key2":#"ZZZ"}];
I want to subtract the array, This should be the expected reuslt,
NSArray *resultArray=#[ #{#"key1":#"C",#"key2":#"CC"},#{#"key1":#"E",#"key2":#"EE"},#{#"key1":#"G",#"key2":#"GG"}];
I tried the below code but didn't working
NSArray *extracted = [array1 valueForKey:#"key1"];
NSMutableSet *pressieContactsSet = [NSMutableSet setWithArray:extracted];
NSMutableSet *allContactSet = [NSMutableSet setWithArray:array2];
[allContactSet minusSet:pressieContactsSet];
NSLog(#"%#",allContactSet);
Please try below code
First get all key1 objects in temporary array. Then apply filter on array1 and check if your array1 object contain arrayKey1 object.
Make sure it will only check for key1 key.
NSArray *arrKey1 = [array2 valueForKey:#"key1"];
NSPredicate *pred = [NSPredicate predicateWithBlock:
^BOOL(id evaluatedObject, NSDictionary *bindings)
{
if ([arrKey1 containsObject:evaluatedObject[#"key1"]])
{
NSLog(#"found : %#",evaluatedObject);
return NO;
}
else
{
NSLog(#"Not found : %#",evaluatedObject);
return YES;
}
}];
NSArray *arrSubtracted = [array1 filteredArrayUsingPredicate:pred];
NSLog(#"%#", arrSubtracted);
Or you can use enumerateObjectsUsingBlock
NSMutableArray *resultArray = [NSMutableArray new];
[array1 enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop)
{
if (![arrKey1 containsObject:obj[#"key1"]]) {
[resultArray addObject:obj];
}
}];
NSLog(#"%#",resultArray);
Hope this will help you.
This should work.
NSArray *array1=#[ #{#"key1":#"A"},#{#"key1":#"C"},#{#"key1":#"E"},#{#"key1":#"G"}];
NSArray *array2=#[ #{#"key1":#"A"},#{#"key1":#"Z"}];
NSMutableSet *pressieContactsSet = [NSMutableSet setWithArray:array1];
NSSet *allContactSet = [NSSet setWithArray:array2];
[pressieContactsSet minusSet:allContactSet];
NSArray *result = [pressieContactsSet allObjects];
NSLog(#"%#",result);
Enjoy!
NSArray *array1=#[ #{#"key1":#"A"},#{#"key1":#"C"},#{#"key1":#"E"},#{#"key1":#"G"}];
NSArray *array2=#[ #{#"key1":#"A"},#{#"key1":#"Z"}];
NSMutableArray *resultArray = [NSMutableArray arrayWithArray:array1];
[resultArray removeObjectsInArray:array2];
NSLog(#"array %#",resultArray);
I have this dictionary:
NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
[dic setObject:#"1" forKey:#"Name"];
[dic setObject:#"1" forKey:#"Last"];
[dic setObject:#"1" forKey:#"Phone1"];
[dic setObject:#"1" forKey:#"Phone2"];
[dic setObject:#"1" forKey:#"Phone3"];
[dic setObject:#"1" forKey:#"Address"];
What is the best way to pull out only the phone numbers?
(this is a dynamic dictionary, sometimes 2 phone numbers and sometimes 5)
First of all, don't set Phone numbers under different keys (Because language gives you array).
NSMutableDictionary *dic = [NSMutableDictionary new];
NSMutableArray *phoneNumbers = [NSMutableArray new];
dic[#"Name"] = #"1";
dic[#"Last"] = #"1" ;
dic[#"Address"] = #"1";
dic[#"Phone"] = phoneNumbers;
[dic[#"Phone"] addObject:#"123"];
[dic[#"Phone"] addObject:#"213"];
[dic[#"Phone"] addObject:#"456"];
// Now retieve phone numbers
for (NSString *phoneNumber in dic[#"Phone"]) {
NSLog(#"Number: %#", phoneNumber);
}
Something like this:
NSSet* passingKeys = [dict keysOfEntriesPassingTest:^BOOL(id key, id obj, BOOL *stop) {
return [key rangeOfString:#"Phone"].location != NSNotFound;
}];
I've read all answers about the subject, but still have my array unsorted. Please, help me with this issue. What's wrong with the code? Thanks in advance.
NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filename error:NULL];
NSDate *date = [attributes fileCreationDate];
NSMutableArray *datesList = [[NSMutableArray alloc] init];
[datesList addObject:date];
NSArray *sortedArray = [[NSArray alloc] init];
sortedArray = [datesList sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2){
if ([obj1 date] > [obj2 date])
{
return (NSComparisonResult)NSOrderedAscending;
}
if ([obj1 date] < [obj2 date])
{
return (NSComparisonResult)NSOrderedDescending;
}
return (NSComparisonResult)NSOrderedSame;
}];
NSLog(#"sortedarray:%#",sortedArray);
First of all, you add to the array only one object :)
Your code should look like:
sortedArray = [datesList sortedArrayUsingComparator:^NSComparisonResult(NSDate *first, NSDate *second){
return [first compare:second];
}];
[NSDate compare:] returns `NSComparisonResult which is fine. You can add ! if you want to have opposite sorting direction.
I have an NSArray some thing like in the following format.
The group array is :
(
"Q-1-A1",
"Q-1-A9",
"Q-2-A1",
"Q-2-A5",
"Q-3-A1",
"Q-3-A8",
"Q-4-A1",
"Q-4-A4",
"Q-10-A2",
"Q-8-A2",
"Q-9-A2",
"Q-7-A1",
"Q-5-A2"
)
Now what i have to do is group the array elements some thing like this.
1 = ( "Q-1-A1","Q-1-A9")
2 = ("Q-2-A1","Q-2-A5",) ...
10 =("Q-10-A2")
can any one please help me how can i achieve this.
Thanks in advance.
Try
NSArray *array = #[#"Q-1-A1",
#"Q-1-A9",
#"Q-2-A1",
#"Q-2-A5",
#"Q-3-A1",
#"Q-3-A8",
#"Q-4-A1",
#"Q-4-A4",
#"Q-10-A2",
#"Q-8-A2",
#"Q-9-A2",
#"Q-7-A1",
#"Q-5-A2"];
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
for (NSString *string in array) {
NSArray *components = [string componentsSeparatedByString:#"-"];
NSString *key = components[1];
NSMutableArray *tempArray = dictionary[key];
if (!tempArray) {
tempArray = [NSMutableArray array];
}
[tempArray addObject:string];
dictionary[key] = tempArray;
}
Create an NSMutableDictionary, then iterate through your 'group array'.
For each NSString object:
get the NSArray of componentsSeparatedByString:#"-"
use the second component to create a key and retrieve the object for that key from your mutable dictionary. If its nil then set it to an empty NSMutableArray.
add the original NSString to the mutable array.
Try this
NSArray *arrData =[[NSArray alloc]initWithObjects:#"Q-1-A1",#"Q-1-A9",#"Q-2-A1",#"Q-2-A5",#"Q-3-A1",#"Q-3-A8",#"Q-4-A1",#"Q-4-A4",#"Q-10-A2",#"Q-8-A2",#"Q-9-A2",#"Q-7-A1",#"Q-5-A2", nil ];
NSMutableDictionary *dictList = [[NSMutableDictionary alloc]init];
for (int i=0; i<[arrData count];i++) {
NSArray *arrItem = [[arrData objectAtIndex:i] componentsSeparatedByString:#"-"];
NSMutableArray *arrSplitedItems = [dictList valueForKey:[arrItem objectAtIndex:1]];
if (!arrSplitedItems) {
arrSplitedItems = [NSMutableArray array];
}
[arrSplitedItems addObject:[arrData objectAtIndex:i]];
[dictList setValue:arrSplitedItems forKey:[arrItem objectAtIndex:1]];
}
NSArray *sortedKeys =[dictList allKeys];
NSArray *sortedArray = [sortedKeys sortedArrayUsingComparator:^(id str1, id str2) {
return [((NSString *)str1) compare:((NSString *)str2) options:NSNumericSearch];
}];
for (int i=0; i<[sortedArray count]; i++) {
NSLog(#"%#",[dictList objectForKey:[sortedArray objectAtIndex:i]]);
}
listOfYourMainArray/// Its YOur main Array;
temArray = (NSArray *)listOfYourMainArray; // Add Your main array to `temArray`.
NSMutableDictionary *lastDic = [[NSMutableDictionary alloc] init]; /// YOu need to creat Dictionary for arrange your values.
for (int i = 0; i< listOfYourMainArray.count; i++)
{
for (int j = 0 ; j < temArray.count; j ++)
{
if (([[temArray objectAtIndex:j] rangeOfString:[NSString stringWithFormat:#"Q-%d", i] options:NSCaseInsensitiveSearch].location != NSNotFound))
{
[lastDic setValue:[temArray objectAtIndex:j] forKey:[NSString stringWithFormat:#"%d", i]];
}
}
}
NSLog(#"%#", lastDic)