How to match the id's to names iphone? - iphone

I am getting Names and ID's from DB... and storing those values in Array... Like Names storing in NamesArray and ID's storing in IDsArray...
Example:
NamesArray - {Peter, Arnold, John,Samuel}
IDsArray - {1, 2, 3,4}
After getting those values from DB... I am sorting NamesArray... It will come like this...
NamesArray Value - {Arnold,John,Peter,Samuel}
How to change the IDsArray according to the NamesArray?
The same scenario is needed for Search functionality....
Example:
I am searching 'P' text in SearchBar... It will show 'Peter' in TableView...
How to get the IDs from idarray according to the Searched Text?
Thanks in advance

You could use an array of dictionaries with keys Name and ID. After you could use NSPredicate for your search and NSSortDescriptor for sorting
yourArray: (
{
id = 1;
name = Peter;
},
{
id = 2;
name = Arnold;
},
{
id = 3;
name = John;
},
{
id = 4;
name = Samuel;
});
Sort
nameDescriptor = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:YES];
nameDescriptors = [NSArray arrayWithObject:nameDescriptor];
sortedArray = [yourArray sortedArrayUsingDescriptors:nameDescriptors];
Filter
NSString *strToFilter = #"P";
NSArray *filteredNames = [yourArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"(name BEGINSWITH[c] %#)", strToFilter]];

For this scenario simple logic can be done.
NamesArray - {Peter, Arnold, John,Samuel}
IDsArray - {1, 2, 3,4}
Have the searched names in separate array which will not affect NamesArray when you search.
searchedNamesArray - {Peter}
after that get the index of the searched object from array
for (NSString *value in searchedNamesArray)
{
NSInteger index = [NamesArray indexOfObject:value];
// you will get the index of the object from which you can use from getting the id from IDsArray
NSLog(#"ID - %#", [IDsArray objectAtIndex:index]);
}

Related

How to access a certain value in an NSArray?

I have an array called someArray. I would like to access the name value of the NSArray. I'm trying to access it using the following, but with out any luck. How do I do it properly?
cell.textLabel.text = [[someArray objectAtIndex:indexPath.row] objectForKey:#"name"];
some array {
haserror = 0;
headers = {
code = 0;
haserror = 0;
nodeid = "fe1.aaaaaa.2.undefined";
time = 16;
};
results = (
{
coords = (
"44.916667",
"8.616667"
);
id = 2;
key = alessandria;
name = Alessandria;
state = Piemonte;
zip = 1512;
},
{
coords = (
"43.616944",
"13.516667"
);
id = 3;
key = ancona;
name = Ancona;
state = Marche;
zip = 601;
},
}
As far as i see from you data model, the key name is a node under the key results. You can use this data model as a dictionary map, the code snippet below must give you what you need..
NSDictionary *myObject = [[someArray objectAtIndex:indexPath.row] objectForKey:#"results"];
cell.textLabel.text = [myObject objectForKey:"name"];
IMPORTANT NOTE: If you have some lopps or some other mechanisms for receiving data, there may be more efficent ways for your sıolution, so please give some more additional info about what you are exactly tryin to do
As others have noted, someArray is a dictionary while results is a key pointing to an array inside of your dictionary. If you want an array of all of the name fields in your results array, you could use valueForKeyPath: on the someArray variable, like this:
NSArray *names = [someArray valueForKeyPath:#"results.name"];
The names variable should now contain "Alessandria", and "Ancona" from the data set your show in your example code.

How to reorder NSMutableDictionary to a NSMutableArray?

I have a NSMutableArray containing NSURLConnection descriptions, like so:
array {
"<NSURLConnection: 0x60eb40>",
"<NSURLConnection: 0x6030e0>",
"<NSURLConnection: 0x602ce0>",
"<NSURLConnection: 0x60c330>",
"<NSURLConnection: 0x662f5a0>",
}
I have also a NSMutableDictionary whose keys are the items from the above NSMutableArray, like so:
dictionary {
"<NSURLConnection: 0x602ce0>" = "Last update: Sep 3, 2012";
"<NSURLConnection: 0x6030e0>" = "Last update: Sep 7, 2012";
"<NSURLConnection: 0x60c330>" = "Last update: Sep 4, 2012";
"<NSURLConnection: 0x60eb40>" = "Last update: Sep 6, 2012";
"<NSURLConnection: 0x662f5a0>" = "Last update: Sep 5, 2012";
}
I need to reorder the NSMutableDictionary to match the same order of the NSMutableArray indexes. Right now I'm doing like this:
int a;
for (a=0; a<self.array.count; a++) {
NSString *key = [self.array objectAtIndex:a];
NSString *object = [self.dictionary objectForKey:key];
if (object !=nil) {
[self.array removeObjectAtIndex:a];
[self.array insertObject:object atIndex:a];
}
}
Is there a better way to reorder this NSMutableDicitioanry to match the order of the NSMutableArray ?
Thank you!
NSDictionary does not guarantee any ordering of it's key/value pairs. There's no way to keep your keys/values in a set order and it doesn't make sense for NSDictionary to work like this. (You use keys not indexes to retrieve values).
If you want your values or keys in a certain order for display purposes you can sort them after retrieving them:
NSArray * sortedKeys = [ [ myDictionary allKeys ] sortedArrayUsingSelector:... ] ;
or
NSArray * sortedKeys = [ [ myDictionary allKeys ] sortedArrayUsingComparator:... ] ;
You could then retrieve the associated objects for the sorted keys if you wanted.
Another option is to maintain 2 separate arrays, one for keys and one for values and keep them in order.

Get index of object in array to look up corresponding object in other array

I have two arrays. One is an array of names and the other is an array made up of strings titled "Yes" or "No". The index path of each name in the "name" array corresponds with the same index path in the "Yes/No" array. For example:
Names Array | Yes/No Array
Person 1 | Yes
Person 2 | No
Person 3 | Yes
What would be the easiest way to look up a person's name (possibly getting the index path of it) and check whether they are "Yes" or "No" in the "Yes/No" array?
Also, I'm not sure if "index path" is the right term to use. If it isn't, I mean the number that an object is in an array.
NSArray has a method called indexOfObject that will return either the lowest index whose corresponding array value is equal to anObject or NSNotFound if no such object is found. If your array of names is unsorted, then use this to get the index that you can then plug in to the Yes/No array. That is, something along these lines:
NSString *answer = nil;
NSUInteger index = [namesArray indexOfObject:#"John Smith"];
if (index != NSNotFound) {
answer = [yesNoArray objectAtIndex:index];
}
return answer;
Because Bavarious asks questions where I assume, here's a better way when the array of names is sorted alphabetically.
int index = [self findName:#"John Smith"];
NSString *answer = nil;
if (index >= 0) {
answer = [yesNoArray objectAtIndex:index];
}
return answer;
where the function findName is a simple binary search:
-(int)findName:(NSString *)name {
int min, mid, max;
NSComparisonResult comparisonResult;
min = 0;
max = [namesArray count]-1;
while (min <= max) {
mid = min + (max-min)/2;
comparisonResult = [name compare:[namesArray objectAtIndex:mid]];
if (comparisonResult == NSOrderedSame) {
return mid;
} else if (comparisonResult == NSOrderedDescending) {
min = mid+1;
} else {
max = mid-1;
}
}
return -1;
}
Trying to keep two arrays synchronized is just asking for trouble. It can be done, of course, but whenever you modify one array, you have to remember to make a corresponding change to the other. Do yourself a favor and avoid that entire class of bugs by rethinking the way you're storing data.
In this case, you've got a {person, boolean} pair. One option is to store each pair as a dictionary, and then keep an array of those dictionaries. This would be a particularly good plan if you might expand the number of pieces of data beyond the two that you have. Another option would be to just use a dictionary where keys are person names and the values are your yes/no values. This makes the answer to your question very simple:
NSString *yesOrNo = [personDictionary objectForKey:personName];
Getting back to your original question, where you still have the two arrays, the easiest thing to do is to iterate over the person array until you find the person you're looking for, get the index of that name, and then look up the corresponding value in the yes/no array:
for (person in peopleArray) {
if ([person isEqualToString:thePersonYoureLookingFor]) {
yesNoValue = [yesNoArray objectAtIndex:[peopleArray indexOfObject:person];
break;
}
}
That's fine if the number of people in the list isn't too large. If the list could be large, then you'll want to keep the person array sorted so that you can do a binary search. The trouble there, though, is that you're yes/no array is separate, so sorting the personArray while keeping the yes/no array in the right order becomes complicated.
You can also use below of the code, May its useful to you,
NSSortDescriptor *_lastDescriptor = [[NSSortDescriptor alloc] initWithKey:#"" ascending:YES];
NSArray *_lastArray = [NSArray arrayWithObject:_lastDescriptor];
firstCharacterArray = (NSMutableArray *)[[nameIndexesDictionary allKeys]
sortedArrayUsingDescriptors:_lastArray];
//firstCharacterArray = (NSMutableArray *)[[nameIndexesDictionary allKeys]
sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
for (NSString *eachlastIndex in firstCharacterArray)
{
NSSortDescriptor *lastDescriptor = [[NSSortDescriptor alloc] initWithKey:#""
ascending:YES];
//selector:#selector(localizedCaseInsensitiveCompare:)] ;
NSArray *descriptorslast = [NSArray arrayWithObject:lastDescriptor];
[[nameIndexesDictionary objectForKey:eachlastIndex]
sortUsingDescriptors:descriptorslast];
[lastDescriptor release];
}
You can use indexOfObject method to get the index of element.
for example
This will give you index of your object
NSInteger index = [yourArray indexOfObject:objectName];
To see the corresponding element from another array
[anotherArray objectAtIndex:index];
This worked for me. Hope this helps.

Extract the values from NSMutableDictionary

(
{
dateVal = "nov 26, 2010";
price = "1 - 195 kr";
},
{
dateVal = "nov 26, 2010";
price = "425 - 485 kr";
},
{
dateVal = "nov 26, 2010";
price = "415 - 640 kr";
})
How can i extract this NSMutableDictionay?
Help me!
You have plenty of choices (I suggest looking into NSArray class reference)
To get dictionary at specific index (whether dictionary you get is mutable or not depends, I think, on how have you created them and put them in array)
// make sure that index is in array bounds
NSDictionary* dict = [yourArray objectAtIndex:index];
NSLog(#"%#", [dict objectForKey:#"dateVal"]); // log date
NSLog(#"%#", [dict objectForKey:#"price"]); // log price
If you want to iterate through all dictionaries you have then you can use fast enumeration:
for (NSDictionary* dict in yourArray){
...
}
It seems to be an Array which contains Dictionnary.
But Vladimir is right, how did you get this ?
To get an item from a Dictionnary, use this :
[ dictionnary objectForKey:#"keyName" ];
Do you mean converting from this string to NSDictionary? It looks like a JSON String for me, doesn't it?
If it is a JSON String and you want to convert to a NSDictionary, you may want to use TouchJSON, some tutorial here

Obj-C / iPhone: NSArray question

I have an array that looks like this when printed via NSLog:
{
response = "Valid";
updates = (
{
string = "test";
integer = 3493;
},
{
string = "test2";
integer = 55454;
}
);
start-index = 0;
My question is how I can loop through through the "updates" array so that I may print the values for each "string" respectively.
Should be an easy "for" loop or something?
Dave
Assuming you NSLogged data has a type of NSDictionary with name data.
NSArray *updates = [data objectForKey:#"updates"];
for (NSDictionary *update in updates) {
NSLog(#"Update: %# - %#", [update objectForKey:#"string"], [update objectForKey:#"integer"]);
}