retrieving data from NSDictionary with quotes already around the value? - ios

How do i retrieve the value for key in a NSDictionary is the value already has quotes arround it
Code:
for(NSDictionary *dict in jsonData)
{
NSString *firstName = [dict valueForKey:#"name_forenames"];
NSString *lastName = [dict valueForKey:#"name_surnames"];
NSLog (#"%# %#", firstName, lastName);
}
in my dictionary which is :
(
{
"name_forenames" = Jordan;
"name_surnames" = Newton;
}, {
"name_forenames" = Jordan;
"name_surnames" = Newton;
}
)
because it just returns null in my NSLog

The dictionary keys do not really contain quotation marks, that's only how the
description method of a dictionary shows strings that contain special characters.
So
NSString *firstName = [dict objectForKey:#"name_forenames"];
or the new syntax
NSString *firstName = dict[#"name_forenames"];
should just work.
Note that objectForKey: is the dedicated method to retrieve dictionary values.
valueForKey: is for Key-Value Coding trickery.

You insert backslash in front of the quotation mark \".
NSString *firstName = [dict valueForKey:#"\"name_forenames\""];

Related

Parse NSString with colons into NSDictionary

I'm trying to parse a string I have that follows the format below
Key: Object\n
Key: Object\n
Key: Object\n
Into an NSDictionary so that it is more easily accessible to me. My question is: Is there a better way to do this that is already incorporated into obj-c? My first thought would be to form an array based on the separation of the : and the newlines and then use the even values as the keys and the odd values as the objects but that seems a little overcomplicated.
NSString *str = #"Key1: Object1\nKey2: Object2\nKey3: Object3\n";
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
NSArray *lines = [str componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
for (NSString *aKeyValue in lines)
{
NSArray *components = [aKeyValue componentsSeparatedByString:#":"];
if ([components count] != 2) continue; //Bypass stranges lines, like the last one
NSString *key = [components[0] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSString *value = [components[1] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
[dict setObject:value forKey:key];
}
NSLog(#"Dict:\n%#", dict);
This gives:
$> Dict:
{
Key1 = Object1;
Key2 = Object2;
Key3 = Object3;
}
Note: I had to rename your String with different keys, because they need to be unique (else, it would have replace the value keeping only the last one). If it's not the case, you maybe don't want a NSDictionary.
This code should work (in Swift):
func parseString(_ str: String) -> Dictionary<String, String> {
let lines = str.components(separatedBy: .newlines)
var dict = [String: String]()
for line in lines {
let list = line.components(separatedBy: ": ")
if list.count == 2 {
dict[list[0]] = list[1]
}
}
return dict
}
First, we create an array with the lines, then for each line, we extract key and value separated by the colon.
All the solutions offered at the time of writing create an array of lines and then process those lines. NSString provides the method enumerateLinesUsingBlock: to avoid creating this intermediate array of lines. Assuming your string is referenced by the variable str then:
NSMutableDictionary *results = [NSMutableDictionary new];
[str enumerateLinesUsingBlock:^(NSString *line, BOOL *stop)
{
NSArray<NSString *> *kvPair = [line componentsSeparatedByString:#":"]; // split key & value
if (kvPair.count != 2) return; // ignore any line not matching "key : value"
NSString *key = [kvPair[0] stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet]; // remove any whitespace
NSString *value = [kvPair[1] stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];
results[key] = value;
}];
will produce the dictionary in results.
Note: The stop parameter passed to the block is to allow the line enumeration to be terminated early, it is not used in this sample. However if a malformed line is found it could be used to terminate the parsing early.
There is no better way to do this with Objective C. Here is how you could approach this. Separate strings by new line character, then again break each line strings with ":", put left part to key and right part to value.
NSString *string = #"name: Jack Johnson\n\
address: Australia\n\
interest: Singing\n\";
NSString *trimmedString = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSArray *keyValuePairs = [trimmedString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (NSString *keyValuePair in keyValuePairs) {
NSArray *keyValues = [keyValuePair componentsSeparatedByString:#":"];
dict[[keyValues.firstObject stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]] = [keyValues.lastObject stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}
NSLog(#"%#", dict);
Something like this. But this gets pretty nice with swift like so,
let keyValueTuple = string.trimmingCharacters(in: .whitespacesAndNewlines)
.components(separatedBy: .newlines)
.map { line -> (String, String) in
let keyValuePairs = line.components(separatedBy: CharacterSet(charactersIn: ":"))
let key = keyValuePairs.first!.trimmingCharacters(in: .whitespaces)
let value = keyValuePairs.last!.trimmingCharacters(in: .whitespaces)
return (key, value)
}
let dict = Dictionary(uniqueKeysWithValues: keyValueTuple)

string handling in ios

I am getting String data from server in the format below. I want to get the value for every tag like phonenumber and name etc. I am able to convert it in array by comma separator. how to get individual values?
Company:Affiliated CO,Organization:TECHNICAL EDUCATION
SOCIETY,Organization:SINHGAD,Organization:National Basketball Association,Person:Parikshit N. Mahalle,PhoneNumber:81 98 22 416 316,PhoneNumber:9120-24100154,Position:Professor,SportsEvent:NBA.
Say your original string is stored in rawString.
You need to :
1) split the string by ,
NSArray *pieces = [rawString componentsSeparatedByString:#","];
2) for each item in this array, split it by :, and add it to a dictionary :
NSMutableDictionary *dict = [NSMutableDictionary new];
for (NSString *piece in pieces) {
NSArray *splitPiece = [piece componentsSeparatedByString:#":"];
// key is at splitPiece[0], value is at splitPiece[1]
dict[splitPiece[0]] = splitPiece[1];
}
Then you'll have a dictionary of what you wanted in the first place.
But as suggested in the comments, it would be far better (and more flexible) for you to receive JSON data.
Edit: your original string shows there are multiple fields named Organization. The code I've given is not designed to handle such cases, it's up to you to build upon it.
If this data is not being returned as a JSON object then you'll have to go with #Clyrille answer. But if it is JSON then NSJSONSerialization:JSONObjectWithData:options:error: will be the way to go.
EXAMPLE
NSDictionary *json = [NSJSONSerialization
JSONObjectWithData:/*urlResponse*/ options:0 error:nil];
NSString *company = [json objectForKey:#"Company"];
NSString *Organization = [json objectForKey:#"Organization"];
NSString *Person = [json objectForKey:#"Person"];
NSString *PhoneNumber = [json objectForKey:#"PhoneNumber"];
NSString *Position = [json objectForKey:#"Position"];
NSString *SportsEvent = [json objectForKey:#"SportsEvent"];

Taking data argument in a created NSString

How can I send data argument in an already created NSString. I have an NSDictionary:
NSArray *objectsArray=[[NSArray alloc]initWithObjects:#"item id %i",#"random id %i",nil];
NSArray *keysArray=[[NSArray alloc]initWithObjects:#"item",#"random",nil];
NSDictionary *dataDictionary=[[NSDictionary alloc]initWithObjects:objectsArray forKeys:keysArray];
Somewhere down the code I ask for the object in the NSDictionary
NSString *counterString=[dataDictionary objectForKey:#"random"];
How Can I now pass data argument into this retrieved NSString?
so my final string looks like
random id 67
NSString *finalString = [NSString stringWithFormat:counterString, digit];
If you also need to store it in your dictionary add
dataDictionary[#"random"] = finalString;
NSArray *objectsArray=[[NSArray alloc]initWithObjects:#"item id %i",#"random id %i",nil];
NSArray *keysArray=[[NSArray alloc]initWithObjects:#"item",#"random",nil];
NSDictionary *dataDictionary=[[NSDictionary alloc]initWithObjects:objectsArray forKeys:keysArray];
NSString *counterString=[dataDictionary objectForKey:#"random"];
NSString *final = [NSString stringWithFormat:counterString, 67];
dataDictionary[#"random"] = final;

iOS - get specific value from plist

I would like to get the value of NO (from the plist under) into a NSString i got. But I'm stuck.
I used the following code:
//Load Dictionary with wood name cross refference values for image name
NSString *plistCatPath = [[NSBundle mainBundle] pathForResource:#"Numbers" ofType:#"plist"];
NSDictionary *numberDictionary = [[NSDictionary alloc] initWithContentsOfFile:plistCatPath];
self.numberArray = numberDictionary[#"Two"];
// ,[codeForCountryDictionary objectForKey:selectedCountryPicker]
number = [self.policeArray valueForKey:#"NO"];
NSLog(#"Numero: %#", number);
But then I got:
(
012
)
and I only want 012, not with the parentheses.
My Plist:
the "NO" is a NSString key in the "Two" NSDictionary and NSString "012" is the value, for the key "NO"
NSDictionary * dict = numberDictionary[#"Two"];
for (NSString * key in dict) {
NSLog(#"%# %#", key, dict[key]);
}
If you want to get the key for a value from NSDictionary, use
NSDictionary * dict = numberDictionary[#"Two"];
NSArray *temp = [dict allKeysForObject:#"012"];
NSString *key = [temp lastObject];
Note: allKeysForObject returns an NSArray, as more keys, may have the same value assigned

select indexOfObject from NSArray in Xcode by comparing string

Hi I have NSarray values in Xcode. I need to get array indexOfObject by comparing string values.
my array values are
(
{
firstName = lord;
lastname = krishna;
},
{
firstName = priya;
lastname = amirtha;
}
)
If I type first name in textfield and click button means last name want to display in another textfield.
thank you.
To answer the title of your question:
NSString *compareString = #"something";
NSMutableArray *indexesOfMatches = [[NSMutableArray alloc]init];
for (NSString *string in theArray) {
if ([string isEqualToString:compareString]) {
NSNumber *index = [[NSNumber numberWithInterger:[theArray indexOfObject:string]];
[indexOfMatches addObject:index];
}
}
//indexOfMatches will now contain NSNumber objects that represent the indexes of each of the matching string objects in the array
I think that using an NSDictionary would be better for you though. Then you can simply keep the first and last names as Key Value pairs.
NSDictionary *names = #{#"lord" : #"krishna", #"priya" : #"amirtha" };
Then you can just do value for key when you get the first name:
NSString *firstName = #"lord";
NSString *lastName = [names valueForKey:firstName];
Store firstNameArray and lastNameArray a mutable array NSMutableArray.
Using Fast Enumeration. Suppose array is the array you are provided with
for (NSDictionary *item in array) {
[firstNameArray addObject:[item objectForKey:#"firstName"]];
[lastNameArray addObject:[item objectForKey:#"lastName"]];
}
After entering the data in firstNameTextField click the button
Button action method implementation
-(IBAction)btnClicked:(id)sender {
NSInteger index = [firstName indexOfObject:[firstNameTextField text]];
[lastNameTextField setText:[lastName objectAtIndex:index]];
}

Resources