select indexOfObject from NSArray in Xcode by comparing string - ios

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]];
}

Related

Unable to retrieve the data from Dictionary

In my project I am getting response from the server in the form
response:
<JKArray 0x7fa2e09036b0>(
{
id = 23;
name = "Name1";
},
{
id = 24;
name = "Name2";
}
)
From this response array i am retrieving the objects at different indexes and then adding them in a mutableArray and then into a contactsDictionary.
self.contactsDictionary = [[NSMutableDictionary alloc] init];
for(int i=0 ; i < [response count] ; i++)
{
NSMutableArray *mutableArray=[[NSMutableArray alloc] init];
[mutableArray addObject:[response objectAtIndex:i]];
[self.contactsDictionary setObject:mutableArray forKey:[NSString stringWithFormat:#"%i",i]];
}
I want to retrieve data for Key #"name" from the contactsDictionary at some other location in the project. So how to do it.
Thanks in advance....
this is the wrong way like you are setting your contactsDictionary.
replace below line
[self.contactsDictionary setObject:mutableArray forKey:[NSString stringWithFormat:#"%i",i]];
with
[self.contactsDictionary setObject:[mutableArray objectAtIndex :i] forKey:[NSString stringWithFormat:#"%i",i]];
becuase everytime your array have new objects so your contacts dictionary's first value have one object then second value have two object. so you shouldn't do that.
now, if you want to retrieve name then call like
NSString *name = [[self.contactsDictionary objectForKey : #"1"]valueForKey : #"name"];
avoid syntax mistake if any because have typed ans here.
Update as per comment:
just take one mutablearray for exa,
NSMutableArray *arr = [[NSMutableArray alloc]init];
[arr addObject : name]; //add name string like this
hope this will help :)
Aloha from your respond I can give you answer Belo like that according to you response.
for(int i=0;i<[arrRes count];i++);
{
NSString *strId = [NSString stringWithFormat:#"%#",[[arrRes obectAtIndex:i]objectForKey:#"id"]];
NSString *StrName = [NSString stringWithFormat:#"%#",[[arrRes objectAtIndex:i]objectForKey:#"name"]];
NSLog(#"The ID is -%#",strId);
NSLog(#"The NAME is - %#",strName);
}

How to retrieve NSStrings stored in multiple NSArrays inside of an NSArray

I'm building an "invite friends" feature.
It's already working I just have one issue I'm wrestling with.
I'm retrieving my contact list, and every time I select a contact I'm adding them to a NSMutableArray which I'm calling "selectedUser".
So each item in the NSMutableArray at this point are "Dictionaries" and some of the values are "Dictionaries" as well. Especially the "phones" key I'm trying to access and retrieve the value key.
What I'm trying to accomplish is to only retrieve the "phone numbers" in strings stored them inside a NSArray that I can then past to [messageController setRecipients:recipents]; recipents being the array of only NSStrings of phone numbers.
This is my code so far, and what I'm getting is a NSArray with multiple NSArrays in it were each array only has one string being the phone number.
NSArray *titles = [self.selectedUsers valueForKey:#"phones"];
NSArray *value = [titles valueForKey:#"value"];
NSLog(#"Output the value: %#", value);
NSArray *recipents = value;
This is what I get in the log
2016-01-04 12:27:59.721 InviteFriends[4038:1249174] (
(
"(305) 731-7353"
),
(
"(786) 306-2831"
),
(
"(305) 333-3297"
)
)
This is the log of the dictionary itself
{
birthday = "";
company = "";
createdAt = "2015-09-06 16:14:18 +0000";
department = "";
emails = (
);
firstName = "Lola";
firstNamePhonetic = "";
id = 699;
jobTitle = "";
lastName = "";
lastNamePhonetic = "";
middleName = "";
nickName = "";
note = "";
phones = (
{
label = Home;
value = "(305) 503-3957";
}
);
prefix = "";
suffix = "";
updatedAt = "2015-09-23 23:31:25 +0000";
}
)
Thanks
If I am understanding this correctly, on the line where you write
NSArray *value = [titles valueForKey:#"value"];,
You are trying to index the NSArray full of dictionaries using the index "value", which doesn't make sense. You should instead loop through your titles array, pull out the value from each dictionary element, and then append that element to your recipents array.
Here is some sample code that should do what I think you want.
NSArray *titles = [self.selectedUsers valueForKey:#"phones"];
NSMutableArray *recipients = [[NSMutableArray alloc] init];
for (NSDictionary* dict in titles) {
NSString* value = [dict objectForKey:#"value"];
[recipients addObject:value];
}
NSLog(#"Phone Numbers: %#",recipients);
Here is the solution I came up with.
First run a for loop to grab the first key. Then nest another for loop to grab the second key.
NSArray *values = self.selectedUsers;
NSMutableArray *recipients = [[NSMutableArray alloc] init];
NSArray *values = self.selectedUsers;
NSMutableArray *recipients = [[NSMutableArray alloc] init];
for (NSDictionary* dict in values) {
// Grabs phones key
NSDictionary *titles = [dict objectForKey:#"phones"];
for (NSDictionary* dict2 in titles) {
// Grabs the "value" key
NSString* value = [dict2 objectForKey:#"value"];
[recipients addObject:value];
}
}

Order NSArray with objects

I have an NSDictionary with the following data:
(lldb) po allFriends
{
71685207018702188 = {
id = 71685207018702188;
name = "mikeziri ";
username = mi;
};
93374822540641772 = {
id = 93374822540641772;
name = "Alan Weclipse";
username = zuka;
};
96553685978449395 = {
id = 96553685978449395;
name = "Monica Weclipse";
username = amonica;
};
96556113096345076 = {
id = 96556113096345076;
name = Xavier;
username = branko;
};
97017008427632119 = {
id = 97017008427632119;
name = "Dario Weclipse";
username = tarzan;
};
}
I'm sorting these objects based on the name, if they don't have a name, i will use the username. To do that, i create a new NSDictionary with the name and id and at the end of the method i sort them by name. The code to sort them is the following:
- (NSArray*)orderFriends
{
NSMutableDictionary* newFriendsDict = [[NSMutableDictionary alloc] init];
for (int i=0; i<[allFriends count];i++)
{
NSMutableDictionary* friendsDict = [[NSMutableDictionary alloc] init];
NSDictionary* friend = [allFriends objectForKey:[NSString stringWithFormat:#"%#", [sortedKeysFriends objectAtIndex:i]]];
if ([[friend objectForKey:#"name"] length] != 0)
{
[friendsDict setObject:[friend objectForKey:#"id"] forKey:#"id"];
[friendsDict setObject:[NSString stringWithFormat:#"%#", [friend objectForKey:#"name"]] forKey:#"name"];
}
else
{
[friendsDict setObject:[friend objectForKey:#"id"] forKey:#"id"];
[friendsDict setObject:[NSString stringWithFormat:#"%#", [friend objectForKey:#"username"]] forKey:#"name"];
}
[newFriendsDict setObject:friendsDict forKey:[NSNumber numberWithInt:i]];
}
NSArray* sp = nil;
sp = [[newFriendsDict allValues] sortedArrayUsingComparator:^(id obj1, id obj2){
NSString *one = [NSString stringWithFormat:#"%#", [obj1 objectForKey:#"name"]];
NSString *two = [NSString stringWithFormat:#"%#", [obj2 objectForKey:#"name"]];
return [one compare:two];
}];
return sp;
}
The problem is that the end result is wrong:
(lldb) po sp
<__NSArrayI 0x160491a0>(
{
id = 93374822540641772;
name = "Alan Weclipse";
},
{
id = 97017008427632119;
name = "Dario Weclipse";
},
{
id = 96553685978449395;
name = "Monica Weclipse";
},
{
id = 96556113096345076;
name = Xavier;
},
{
id = 71685207018702188;
name = "mikeziri ";
},
)
Case sensitive. make all string small or big.
You could also just change
return [one compare:two];
to
return [one compare:two options: options:NSCaseInsensitiveSearch];
Than it will be ordered alphabetically, no matter if upper or lower case...
Several things: There is no reason to build different dictionaries in order to sort, and good reason NOT to do so.
You already found the method sortedArrayUsingComparator. That takes a block that is used to compare pairs of objects, and returns a sorted array. You can use that method to implement any sorting criteria you want.
I would suggest writing a comparator block that compares the name properties of your objects unless it's blank, and uses username if that's blank. It would only be a few lines of code:
NSArray *sortedFriends = [[allFriends allValues] sortedArrayUsingComparator:
^(NSDictionary *obj1, NSDictionary *obj2)
{
NSString* key1 = obj1[#"name"] ? obj1[#"name"] : obj1[#"username"];
NSString* key2 = obj2[#"name"] ? obj2[#"name"] : obj2[#"username"];
return [key1 caseInsensitiveCompare: key2];
}];
EDIT: I just noticed (from your edit of my post) that you are starting from a dictionary, not an array. So what you want to do is to create a sorted array of all the values in the dictionary? Is it acceptable to discard the keys for all the items in your dictionary, and end up with a sorted array of the values?
The other thing you could do would be to build an array of the dictionary keys, sorted based on your sort criteria. Then you could use the array of keys to fetch the items from your dictionary in sorted order.

Xcode NSDictionary Subdictionary

I have dictionary which i want to use to fill a tableview. It is parsed by JSON.
My dictionary looks like that:
NSLog(#"%#",temp);
// OUTPUT //
(
{
ShootingDate = "2013-07-29 00:00:00";
ShootingID = 1;
ShootingName = Testshooting;
},
{
ShootingDate = "2013-06-12 00:00:00";
ShootingID = 2;
ShootingName = Architektur;
}
)
Dictionary looks in XCode like that:
Now i want to fill a table with that data. Each row should display ShootingDate,ShootingID and ShootingName but i am not able to access these keys.
Anyone a suggestion?
First of all temp is not dictionary it is NSArray and u can get it as
for (NSDictionary *dictionary in temp) {
[dictionary valueForKey:#"ShootingDate"];
[dictionary valueForKey:#"ShootingID"];
[dictionary valueForKey:#"ShootingName"];
}
You can get your dictionary in cellforRow as
NSDictionary *tempDicts=[temp objectAtIndex:indexPath.row];
cell.textLabel.text=[NSString stringWithFormat:#"id=%#,date=%#,name=%#",[tempDicts valueForKey:#"ShootingID"],[tempDicts valueForKey:#"ShootingDate"],[tempDicts valueForKey:#"ShootingName"]];
you can access these keys as
NSString *str_ShootingDate = [[temp objectAtIndex:indexpath.row]
objectForKey:#"ShootingDate"]; //you can change this key with ShootingID
//or ShootingName

Using NSPredicate to filter an object and a key(that needs to be split)

I have the following dictionary set up(Object, Key)
0, "10;0.75,0.75"
1, "0;2.25,2.25"
3, "1;3.5,2.0"
4, "1;4.5,3.0"
5, "2;6.0,5,0"
What I want to filter will be based on the object AND the key. The object is a NSNumber. The key is a string but i really don't want the entire string. I want to split the string separated by the semicolon and take the first index of the split which would yield the strings 10,0,1,1 or 2 depending on which object I was looking for.
As a specific example:
Are there any keys that are equal to #"1" with an object that is greater than 3.
In this case i should expect back YES since object 4 has a key that is equal to #"1", after i do the split.
I guess I was looking for a clever way to define a NSPredicate to do the split on the key separated by the semicolon and then filter(compare, etc) based on that. Let me know if you have any questions or need additional info.
A very naive implementation that I could think of
- (BOOL)hasKey:(NSString *)key withValueGreaterThan:(id)object{
NSDictionary *dictionary = #{#"10;0.75,0.75": #0,
#"0;2.25,2.25" : #1,
#"1;3.5,2.0" : #3,
#"1;4.5,3.0" : #4,
#"2;6.0,5,0" : #5};
NSPredicate *keyPredicate = [NSPredicate predicateWithFormat:#"SELF BEGINSWITH %#",key];
NSArray *filteredKeys = [[dictionary allKeys]filteredArrayUsingPredicate:keyPredicate];
for (NSString *k in filteredKeys) {
NSNumber *value = dictionary[k];
if (value>object) {
return YES;
}
}
return NO;
}
Use
BOOL hasValue = [self hasKey:#"1;" withValueGreaterThan:#3];
Sample Code:
NSDictionary* dict = #{ #"10;0.75,0.75":#0,
#"0;2.25,2.25":#1,
#"1;3.5,2.0":#3,
#"1;4.5,3.0":#4,
#"2;6.0,5,0":#5};
__block NSString* foundKey = nil;
[dict enumerateKeysAndObjectsUsingBlock:^(NSString* key, NSNumber* obj, BOOL *stop) {
//here goes condition
//get substr
NSArray* arr = [key componentsSeparatedByString:#";"];
int num = [[arr objectAtIndex:0]integerValue];
if ((num == 1)&&([obj integerValue]>3)) {
foundKey = key;
stop = YES;
}
}];
if (foundKey) {
NSLog(#"%#:%#",foundKey,[dict objectForKey:foundKey]);
}
Just use the following method:
-(BOOL)filterFromDictionary:(NSDictionary*)dict keyEqual:(NSString*)key greaterthanObj:(NSString*)obj
{
NSArray *allKeys = [dict allKeys];
for (NSString *eachkey in allKeys) {
NSString *trimmedKey = [self trimKeyuntill:#";" fromString:eachkey];
NSString *trimmedValue = [dict objectForKey:eachkey];
if ([trimmedKey isEqualToString:key] && [trimmedValue intValue] > [obj intValue]) {
return YES;
}
}
return NO;
}
call the above method with your dictionary like:
NSDictionary *dict = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:#"1",#"1",#"3",#"4",#"5", nil] forKeys:[NSArray arrayWithObjects:#"10;0.75,0.75",#"0;2.25,2.25",#"1;3.5,2.0",#"1;4.5,3.0",#"2;6.0,5,0", nil]];
[self filterFromDictionary:dict keyEqual:#"1" greaterthanObj:#"3"]
I assumed all your objects are nsstrings. otherwise change the intValue

Resources