how to create a NSDictionary consisting of NSArray of NString for key and bunch of int for the value? - objective-c

here is the problem :
NSArray * alphabets = [NSArray arrayWithObjects:#"a",#"b",#"c",#"d",#"e",#"f",#"g",#"h",#"i",#"j",#"k",#"l",#"m",#"n",#"o",#"p",#"q",#"r",#"s",#"t",#"u",#"v",#"w",#"x",#"y",#"z",nil];
NSDictionary * alphaToNum = [NSDictionary dictionaryWithObject:alphabets forKey:1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26];
//I know above line meant to not work I just brought it here as an example
how can I create a dictionary just like above which is working?

You can only use objects as keys or values in a NSDictionary, so you have to use NSNumber as wrapper for your integer key.
NSMutableDictionary *alphaToNum = [NSMutableDictionary dictionary];
NSArray *alphabet = [NSArray arrayWithObjects:#"a",#"b",#"c",#"d",#"e",#"f",#"g",#"h",#"i",#"j",#"k",#"l",#"m",#"n",#"o",#"p",#"q",#"r",#"s",#"t",#"u",#"v",#"w",#"x",#"y",#"z",nil];
NSInteger index = 0;
for(NSString *character in alphabet)
{
index ++;
[alphaToNum setObject:character forKey:[NSNumber numberWithInteger:index]];
}

Related

How can I swap keys and values in NSDictionary?

I want to know how to invert a NSDictionary.
I've seen some crazy code like
NSDictionary *dict = ...;
NSDictionary *swapped = [NSDictionary dictionaryWithObjects:dict.allKeys forKeys:dict.allValues];
which is according to documentation not safe at all since the order of allValues and allKeys is not guaranteed.
NSDictionary *dict = ...;
NSMutableDictionary *swapped = [NSMutableDictionary new];
[dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
swapped[value] = key;
}];
Note that the values should also conform to the NSCopying protocol.
You're right, that code is crazy, but there are two ways to get an array of the values in the order given by an array of keys:
NSArray * keys = [dict allKeys];
NSArray * vals = [dict objectsForKeys:keys notFoundMarker:nil];
NSDictionary * inverseDict = [NSDictionary dictionaryWithObjects:keys
forKeys:vals];
Or
NSUInteger count = [dict count];
id keys[count];
id vals[count];
[dict getObjects:vals andKeys:keys];
NSDictionary * inverseDict = [NSDictionary dictionaryWithObjects:keys
forKeys:vals
count:count];
The former is obviously a lot nicer. As noted in hfossli's answer, the objects that were values in the original dictionary must conform to NSCopying in order to be used as keys in the inversion.

NSString to NSArray and editing every object

I have an NSString filled with objects seperated by a comma
NSString *string = #"1,2,3,4";
I need to seperate those numbers and store then into an array while editing them, the result should be
element 0 = 0:1,
element 1 = 1:2,
element 2 = 2:3,
element 3 = 3:4.
How can i add those to my objects in the string ??
Thanks.
P.S : EDIT
I already did that :
NSString *string = #"1,2,3,4";
NSArray *array = [string componentsSeparatedByString:#","];
[array objectAtIndex:0];//1
[array objectAtIndex:1];//2
[array objectAtIndex:2];//3
[array objectAtIndex:3];//4
I need the result to be :
[array objectAtIndex:0];//0:1
[array objectAtIndex:1];//1:2
[array objectAtIndex:2];//2:3
[array objectAtIndex:3];//3:4
In lieu of a built in map function (yey for Swift) you would have to iterate over the array and construct a new array containing the desired strings:
NSString *string = #"1,2,3,4";
NSArray *array = [string componentsSeparatedByString:#","];
NSMutableArray *newArray = [NSMutableArray arrayWithCapacity:array.count];
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[newArray addObject:[NSString stringWithFormat:#"%lu:%#", (unsigned long)idx, obj]];
}];
The first thing you need to do is separate the string into an array of component parts - NSString has a handy method for that : '-componentsSeparatedByString'. Code should be something like this :
NSArray *components = [string componentsSeparatedByString:#","];
So that gives you 4 NSString objects in your array. You could then iterate through them to make compound objects in your array, though you arent exactly clear how or why you need those. Maybe something like this :
NSMutableArray *resultItems = [NSMutableArray array];
for (NSString *item in components)
{
NSString *newItem = [NSString stringWithFormat:#"%#: ... create your new item", item];
[resultItems addObject:newItem];
}
How about this?
NSString *string = #"1,2,3,4";
NSArray *myOldarray = [string componentsSeparatedByString:#","];
NSMutableArray *myNewArray = [[NSMutableArray alloc] init];
for (int i=0;i<myOldarray.count;i++) {
[myNewArray addObject:[NSString stringWithFormat:#"%#:%d", [myOldarray objectAtIndex:i], ([[myOldarray objectAtIndex:i] intValue]+1)]];
}
// now you have myNewArray what you want.
This is with consideration that in array you want number:number+1

Objective-C: Sort keys of NSDictionary based on dictionary entries

OK so I know that dictionaries can't be sorted. But, say I have NSMutableArray *keys = [someDictionary allKeys]; Now, I want to sort those keys, based on the corresponding values in the dictionary (alphabetically). So if the dictionary contains key=someString, then I want to sort keys based on the strings they correspond to. I think its some application of sortUsingComparator but its a little out of my reach at this point.
NSArray *keys = [someDictionary allKeys];
NSArray *sortedKeys = [keys sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
NSString *first = [someDictionary objectForKey:a];
NSString *second = [someDictionary objectForKey:b];
return [first compare:second];
}];
NSDictionary *dict = // however you obtain the dictionary
NSMutableArray *sortedKeys = [NSMutableArray array];
NSArray *objs = [dict allValues];
NSArray *sortedObjs = [objs sortedArrayUsingSelector:#selector(compare:)];
for (NSString *s in sortedObjs)
[sortedKeys addObjectsFromArray:[dict allKeysForObject:s]];
Now sortedKey will contain the keys sorted by their corresponding objects.
Sort keys of NSDictionary based on dictionary keys
Abobe is for returning a sorted array with based on dictionary content, this is for returning an array sorted by dictionary key:
NSArray *keys = [theDictionary allKeys];
NSArray *sortedKeys = [keys sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
return [a compare:b];
}];
NSMutableArray *sortedValues = [NSMutableArray new];
for(NSString *key in sortedKeys)
[sortedValues addObject:[dictFilterValues objectForKey:key]];
Just write it here cause I didn't find it anywhere: To get an alphanumeric sorted NSDictionary back from an NSDictionary based on the value - which in my case was neccessary - you can do the following:
//sort typeDict alphanumeric to show it in order of values
NSArray *keys = [typeDict allKeys];
NSArray *sortedKeys = [keys sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
NSString *first = [typeDict objectForKey:a];
NSString *second = [typeDict objectForKey:b];
return [first compare:second];
}];
NSLog(#"sorted Array: %#", sortedKeys);
NSMutableDictionary *sortedTypeDict = [NSMutableDictionary dictionary];
int counter = 0;
for(int i=0; i < [typeDict count]; i++){
NSString *val = [typeDict objectForKey:[sortedKeys objectAtIndex:counter]];
NSString *thekey = [sortedKeys objectAtIndex:counter];
[sortedTypeDict setObject:val forKey:thekey];
counter++;
}
NSLog(#"\n\nsorted dict: %#", sortedTypeDict);
Not a big deal!
If any value from the dictionary is null then use this code
NSArray *keys = [typeDict allKeys];
NSSortDescriptor *sd = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES];
NSArray *sortedKeys = [keys sortedArrayUsingDescriptors:#[sd]];
NSLog(#"SORT 1 %#",sortedKeys);
NSMutableDictionary *sortedTypeDict = [NSMutableDictionary dictionary];
int counter = 0;
for(int i=0; i < [typeDict count]; i++){
id val = [typeDict objectForKey:[sortedKeys objectAtIndex:counter]];
NSString *thekey = [sortedKeys objectAtIndex:counter];
[sortedTypeDict setObject:val forKey:thekey];
counter++;
}
NSLog(#"\n\nsorted dict: %#", sortedTypeDict);

can't get value from NSDictionary which expected to have NSNumber as output

I have created a NSDictionary like following :
NSArray * alphabets = [NSArray arrayWithObjects:#"a",#"b",#"c",#"d",#"e",#"f",#"g",#"h",#"i",#"j",#"k",#"l",#"m",#"n",#"o",#"p",#"q",#"r",#"s",#"t",#"u",#"v",#"w",#"x",#"y",#"z",nil];
alphaToNum = [NSMutableDictionary dictionary];
numToAlpha = [NSMutableDictionary dictionary];
for(NSString* character in alphabets)
{
[alphaToNum setObject:[NSNumber numberWithInteger:index] forKey:character];
[numToAlpha setObject:character forKey:[NSNumber numberWithInteger:index]];
index++;
}
now I want to access to "numToAlpha" like following :
NSInteger code1;
NSNumber * nn = [numToAlpha objectForKey:code1];
and I'll get error whereas in manual for objectforkey it clearly said (id)objectforkey(id) which means anything!
NSInteger is not an object. id refers to any object type. You need to use [NSNumber numberWithInteger:code1] as you are already doing in your code sample.

How to convert nsstring to nsdictionary?

I have gone through following question.
Convert NSString to NSDictionary
It is something different then my question.
My question is as follows.
NSString *x=#"<Category_Id>5</Category_Id><Category_Name>Motos</Category_Name><Category_Picture>http://192.168.32.20/idealer/admin/Picture/icon_bike2009819541578.png</Category_Picture>";
Now I want to convert this into a dictionary, something like this,
dictionary key = Category_Id | value = 5
dictionary key = Category_Name | value = ???
dictionary key = Category_Picture | value = ???
I don't know how to perform this.
Not the fastest implementation, but this would do the trick (and doesn’t require any third party libraries):
#interface NSDictionary (DictionaryFromXML)
+ (NSDictionary *)dictionaryFromXML:(NSString *)xml;
#end
#implementation NSDictionary (DictionaryFromXML)
+ (NSDictionary *)dictionaryFromXML:(NSString *)xml
{
// We need to wrap the input in a root element
NSString *x = [NSString stringWithFormat:#"<x>%#</x>", xml];
NSXMLDocument *doc = [[[NSXMLDocument alloc] initWithXMLString:x
options:0
error:NULL]
autorelease];
if (!doc)
return nil;
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (NSXMLElement *el in [[doc rootElement] children])
[dict setObject:[el stringValue] forKey:[el name]];
return dict;
}
#end
If it's XML then you can use an NSXMLParser. If it's not then you can write your own parser.
You could do it with a regular expression... Something like <([^>]+)>([^<]+)</\1> would grab the key into capture 1 and the value into capture 2. Iterate over the matches and build the dictionary.
This uses RegexKitLite:
NSString * x = #"<Category_Id>5</Category_Id><Category_Name>Motos</Category_Name><Category_Picture>http://192.168.32.20/idealer/admin/Picture/icon_bike2009819541578.png</Category_Picture>";
NSString * regex = #"<([^>]+)>([^<]+)</\\1>";
NSArray * cap = [x arrayOfCaptureComponentsMatchedByRegex:regex];
NSMutableDictionary * d = [NSMutableDictionary dictionary];
for (NSArray * captures in cap) {
if ([captures count] < 3) { continue; }
NSString * key = [captures objectAtIndex:1];
NSString * value = [captures objectAtIndex:2];
[d setObject:value forKey:key];
}
NSLog(#"%#", d);