Find object by name in NSMutableArray - ios

I have a generic person object with properties personName, lastName, and age. I am storing the user input into an NSMutableArray and I wanted to find a under by his/her name in the array. I have tried finding a bunch of different solutions but none that quite really work.
This is my main.m
#autoreleasepool {
char answer;
char locatePerson[40];
//Create mutable array to add users for retrieval later
NSMutableArray *people = [[NSMutableArray alloc] init];
do{
Person *newPerson = [[Person alloc]init];
[newPerson enterInfo];
[newPerson printInfo];
[people addObject:newPerson];
NSLog(#"Would you like to enter another name?");
scanf("\n%c", &answer);
}while (answer == 'y');
NSLog(#"Are you looking for a specific person?");
scanf("%c", locatePerson);
//This is where I need help
int idx = [people indexOfObject:]
}
This is very basic but I am new to objective-c and I wanted to try and find the user by name. The solutions I've seen have used the indexesOfObjectsPassingTest method. But I was wondering if I can't just use the indexOfObjectmethod the way I did there to locate a person by its name?
Any help is appreciated.

This is one of those hard problems you should avoid with some up-front design. If you know that you are putting things into a collection class and will need to get them out again based on some attribute (rather than by order of insertion) a dictionary is the most efficient collection class.
You can use a NSDictionary keyed with Person's name attribute. You can still iterate over all the objects but you will avoid having to search the whole collection. It can take a surprisingly long time to find a matching attribute in a NSArray! You wouldn't even have to change your Person object, just do
NSDictionary *peopleDictionary = #{ person1.name : person1, person2.name : person2 };
or add them one by one as they are created into a NSMutableArray.

You can try something like this assuming that 'name' is a property for your Person class.
NSUInteger i = 0;
for(Person *person in people) {
if([person.name isEqualToString:locatePerson]) {
break;
}
i++;
}

Related

How can I implement my logic properly to populate my UITableView

Sorry guys, this problem I am running into is pretty trivial. I just can't wrap my head around it so hope someone can help me. Your help is really appreciated. I am getting JSON data through NSURLConnectDelegate with a web API. I get something like this back:
(
{
id = 340
name = Vicent },
{
id = 339
name = Johny },
{
id = 338
name = Eric }
)
and I save it in a NSMutableArray as a global variable. Now, I have a NSSet of "ids". For example:
{
340, 339
}
In the numberOfRowsInSection, I return the set's count. I am trying to load only the ids in the NSSet from the array with the data saved from the webAPI, so I do something like this in cellForRowIndexPath:
for (NSNumber *num in [set allObjects]) {
NSString *newString = [[savedArray objectAtIndex:indexPath.row]
NSString *new = [num stringValue];
if ([new isEqual:newString]) {
}}
How can I just populate the ids I want?
The JSON makes it look like you have an array of dictionaries, which is a reasonable data structure to use as the data source for a table view.
It sounds like you're trying to filter your array to only include the items that are in your set. Is that right?
If so, you could write code that would create a new array containing the subset of your array elements who's ID is also in your set. There are at least a half-dozen ways to do that. One fairly simple approach would be to use the NSArray method indexesOfObjectsPassingTest. You'd pass that method a block of code that would check each array element to see if it's id object was in your set.
That would give you an NSIndexSet with the indexes of the items in your array who's ID are in your set. Then you could use the NSArray method objectsAtIndexes to get an array of only the objects that are also in the set. Something like this (Assuming that your array of dictionaries is called savedArray and your set is called allObjects:
//get the indexes of items in the array savedArray who's id appears in the set allObjects
NSIndexSet *indexes = [savedArray indexesOfObjectsPassingTest:
^(NSDictionary *obj,
NSUInteger idx,
BOOL *stop)
{
return [allObjects member: obj[#"id"]] != nil;
}
];
//Now build an (immutable) array of just the objects who's ID are in the set
NSArray *subArray = [savedArray objectsAtIndexes: indexes];
The array subArray created above is immutable. If you need a mutable array you would need to make a mutable copy, which is a one-line change.
Disclaimer: I still struggle a little with block syntax, so the above might not be exactly correct, but it gives you the general idea.

IOS Objective C - Updating NSArray values from another NSArray

I have a NSArray with objects Called Houses, each object has 3 fields = id,address,price
I can set the value by using
[house setValue:#"£100k" forKey:#"price"];
However I have another NSArray called Movements, each object has 2 fields, id & price
so how do I update the 1st array with details from the 2nd array.. in english it I trying to do "Update house price with movement price where house id = movement id"
Thanks in advance
Sounds like you want a double loop:
for (House* house in houses)
for (Movement* movement in movements)
{
if (house.id == movement.id)
house.price = movement.price
}
If there will only be one such instance you may want to break early, you'll need an extra BOOL for this:
BOOL breaking = false;
for (House* house in houses)
{
for (Movement* movement in movements)
{
if (house.id == movement.id)
{
house.price = movement.price
breaking = true;
break;
}
}
if (breaking) break;
}
Edit: If you are doing this kind of thing frequently, you probably want to construct a dictionary keyed on the id field so you can look up an object quickly rather than by looping the whole array. NSDictionary is the class you want for this, also note that keys must be objects, so if your id field is an int you'll want to convert it to an NSNumber with [NSNumber numberWithInt:] before using it as a key.

How to check to see if an object exists in NSMutableArray without knowing the index, and replace it if it exists, in iOS?

I have an NSMutableArray that contains objects of type Person. The Person object contains parameters of NSString *name, NSString *dateStamp, and NSString *testScore. What I would like to do using fast enumeration, is to check to see in the NSMutableArray *testResults, is see if an object with the same name parameter exists.
If it does, then I want to replace the existing object in the NSMutableArray, with the object that I am about to insert which will have the most current dateStamp, and testScore values. If an object with no matching name parameter is found, then simply insert the object that I have.
My code so far looks like this:
This is the code that creates my object that I am about to insert:
Person *newPerson = [[Person alloc] init];
[newPerson setPersonName:newName]; //variables newName, pass, and newDate have already been
[newPerson setScore:pass]; //created and initialized
[newPerson setDateStamp:newDate];
and here is the code where I try to iterate through the NSMutableArray to see if an object with the same name parameter already exists:
for (Person *checkPerson in personList) { //personList is of type NSMutableArray
if (newPerson.newName == checkPerson.name) {
//here is where I need to insert the code that replaces checkPerson with newPerson after a match has been found
}
else {
personList.addObject(newPerson); //this is the code that adds the new object to the NSMutableArray when no match was found.
}
}
It's not a very complicated problem, but I am confused as to how to go about finding a match, and then replacing the actual object without knowing ahead of time what index the object resides in.
You want to use indexOfObjectPassingTest to look for a match:
NSInteger indx = [personList indexOfObjectPassingTest:^BOOL(Person *obj, NSUInteger idx, BOOL *stop) {
return [obj.name isEqualToString:newPerson.name];
}];
if (indx != NSNotFound) {
[personList replaceObjectAtIndex:indx withObject:newPerson];
}else{
[personList addObject:newPerson];
}
Notice that I used isEqualToString: to compare the two strings not ==. That mistake has been asked about and answered a million times on this forum.
You have some inconsistency in your naming. In the question, you say the Person objects have a name property, but when you create a new person you use setPersonName, which would imply that the property name is personName. I assumed, just name in my answer.

NSMutableArray or NSMutableDictionary : which is best for this scenario?

I need to scroll through several thousands of words to categorize them... to determine which words have the same pattern. (this part works)
For example, a four letter word that has two m's in 2nd & 4th position represent a pattern ("-m-m"). Once I have gone through all the words, I will know how many words there are for any given pattern. I am scrolling through now, but the problem I have is 'remembering' how many words I have in any given pattern.
I was thinking of using NSMutableDictionary and have the key be the pattern ('-m-m-') and the object represent the count of that pattern. This means every time I come across a pattern, I look up that pattern in the dictionary, get the key, increment the key, and put it back in the dictionary.
I need help with both the decision and syntax for performing this task.
Thank You
The answer to your question was this part of your (given) question "I will know how many words there are for any given pattern.". I would use an array of dictionary. You use the dictionary to store key value pair: a known pattern and the count. And you use the array to store those KVP records. So the next time you detect a pattern, search for the array for that record (dictionary), if found, increment the count. If not, create new record and set the count to 1.
Added sample code:
#define kPattern #"Pattern"
#define kPatternCount #"PatternCount"
-(NSMutableDictionary *)createANewDictionaryRecord:(NSString *) newPattern
{
int count = 1;
NSMutableDictionary *myDictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:
newPattern, kPattern,
[NSString stringWithFormat:#"%i",count], kPatternCount,
nil];
return myDictionary;
}
-(void)addANewPatternToArray:(NSMutableDictionary *)newDictionary
{
// NSMutableArray *myArrayOfDictionary = [[NSMutableArray alloc]init]; // you need to define it somewhere else and use property etc.
[self.myArrayOfDictionary addObject:newDictionary]; //or [self.myArrayOfDictionary addObject:newDictionary]; if you follow the recommendation above.
}
-(BOOL)existingPatternLookup:(NSString *)pattern
{
for (NSMutableDictionary *obj in self.myArrayOfDictionary)
{
if ([[obj objectForKey:kPattern] isEqual:pattern])
{
int count = [[obj objectForKey:kPatternCount] intValue] + 1;
[obj setValue:[NSString stringWithFormat:#"%i",count] forKey:kPatternCount];
return YES;
}
}
[self.myArrayOfDictionary addObject:[self createANewDictionaryRecord:pattern]];
return NO;
}
-(void)testData
{
NSMutableDictionary *newDict = [self createANewDictionaryRecord:#"mmm"];
[self addANewPatternToArray:newDict];
}
-(void) printArray
{
for (NSMutableDictionary * obj in self.myArrayOfDictionary)
{
NSLog(#"mydictionary: %#", obj);
}
}
- (IBAction)buttonPressed:(id)sender
{
if ([self existingPatternLookup:#"abc"])
{
[self printArray];
} else
{
[self printArray];
}
}
Not being an objective C expert but solving this problem in java before, I would say a dictionary(I used a map when doing it in java) is the best way. Check if the key(pattern) already exist if so increment that count else put a new one in the dictionary.
EDIT
If you want to not just get the count of a pattern, but in fact tell which words fall under that pattern, I would use a dictionary of strings to mutable arrays. In the arrays you store the words and the key to the array is the pattern(as a string), similar code as above but instead of just incrementing the count, you have to add the new word to the array.
The only difference in NSDictionary and NSMutableDictionary is that one can have objects added to it. I think your implementation is good, but English is a complex language. It would be more efficient to parse out the string with regex than to set a key for it.
Why don't you use NSCountedSet instead:
NSCountedSet Class Reference
..which is available in iOS 2.0 and later?
Each distinct object inserted into an NSCountedSet object has a counter associated with it. NSCountedSetkeeps track of the number of times objects are inserted [...] Thus, there is only one instance of an object in an NSSet object even if the object has been added to the set multiple times. The count method defined by the superclass NSSet has special significance; it returns the number of distinct objects, not the total number of times objects are represented in the set.
Then use:
- (NSUInteger)countForObject:(id)anObject
Use a dictionary of NSMutableArrays, and check for the existence of each search key as you recommended. If the key doesn't exist, add an NSMutableSet or NSMutableArray (depending on your needs) for the searched key type "-m-m" for example, and then add to the set or array for that key.

setObject:forKey: of NSMutableDictionary overwrites all data in dictionary

for ( int cnt = 0 ; cnt < nPeople ; cnt++ )
{
ABRecordRef ref = CFArrayGetValueAtIndex(allPeople, cnt);
NSString *firstName = (NSString *)ABRecordCopyValue(ref, kABPersonFirstNameProperty);
NSString *lastName = (NSString *)ABRecordCopyValue(ref, kABPersonLastNameProperty);
NSString *fullName;
/* skipped code at here : code to merge firstName and lastName to fullName. In my country, many of us don't separate first name and last name */
// tempKeyString : NSString variable that has key of fullNameArray value for nameDictionary.
// fullNameArray : to keep some fullName variables for tempKeyString.
if (!tempKeyString) // there's no tempKeyString, a.k.a. it's the first fullName.
{
// it's not important to know about GetUTF8String:fullName. It's for my own language.
tempKeyString = [self GetUTF8String:fullName];
[fullNameArray addObject:fullName];
}
else
{
if ([tempKeyString characterAtIndex:0] == [[self GetUTF8String:fullName] characterAtIndex:0]) // if fullName has the same tempKey with fullNameArray.
{
[fullNameArray addObject:fullName];
}
else // if fullName has different tempKey with fullNameArray.
{
//tempKey : key data for fullNameArray
NSString *tempKey = [tempKeyString substringToIndex:1];
// tempDict : to keep the deep copy of nameDictionary before adding new key.
NSDictionary *tempDict = [nameDictionary mutableDeepCopy];
// add new key (tempKey) with new value (fullNameArray)
// PROBLEM : ALL values (including previous values) in dictionary(nameDictionary) are overwritten to a new value(fullNameArray).
[nameDictionary setObject:fullNameArray forKey:tempKey];
//empties fullNameArray so that it can get the new fullName of the new tempKey.
[fullNameArray removeAllObjects];
//refresh tempKeyString, and add the new fullName.
tempKeyString = [self GetUTF8String:fullName];
[fullNameArray addObject:fullName];
...
}
}
}
I'm trying to make a NSMutableDictionary object from the contacts of my iPhone. Why I make a NSMutableDictionary typed object is that I need indexes for contacts, and it doesn't look easy to make indexes from ABAddressRef typed object directly. I also need to make searching function..
There was no problem when I just coded, but after debugging the only problem makes me crazy. After I apply the array named fullNameArray with the key named tempKey to the namedDictionary, I can find the nameDictionary has all values with them of fullNameArray. All previous data were overwritten! I tried to make a deep copied version of previous nameDictionary before applying fullNameArray and copy it to the newer nameDictionary. However, when I checked the breakpoint at the third line, I can't find the previous data at the tempDict.
I added more codes and comments. It might help more than my explanation.. any questions are pleased!
I tried to find the reason from here - StackOverflow -, and other webpages all the night, but I couldn't find any similar problems.. please help me! Thank you so much in advance!!
The reason why it get emptied is because
[nameDictionary setObject:fullNameArray forKey:tempKey];
here, you set up your dictionary with the object "fullNameArray", then
[fullNameArray removeAllObjects];
remove all the values inside this array, effectively, removing your object in the "nameDictionary", they are the same object, it's not a deep copy of fullNameArray that you store inside your dictionary. Why did you need to store anything into your array anyway? You're only storing 1 value.
[nameDictionary setObject:fullName forKey:tempKey];
will do what you need. Sorry if I mistaken your question, it's quite hard to understand

Resources