How to create a query in NSMutableArray and print out results? - iphone

I have got a NSMutableArray that is structured as follow:
{
{
AccountNumber:Test1
Type: Electricity
}
{
AccountNumber:Test2
Type: Water
}
{
AccountNumber:Test3
Type: Water
}
}
How to print out the account number that are in Water type?
What I have tried is as follow:
- (NSUInteger)indexOfObjectIdenticalTo:(id)data{ return data; }
But I didn't understand how to do it.

Check out NSPredicate. It will allow to you essentially define a query and apply it to your array to filter the results. This is much faster than a iterative loop through the array to find what you are looking for. For your example, you would simply need to do the following:
NSString *type = #"Water";
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"Type == %#", type];
NSArray *results = [myArray filteredArrayUsingPredicate:predicate];

Assuming each item in the array is a NSDictionary, and all the keys/values are NSStrings, you could do something like this:
for (NSDictionary *dict in myArray) {
if ([[dict objectForKey:#"Type"] isEqualToString:#"Water"]) {
NSLog(#"Account number %#", [dict objectForKey:#"AccountNumber"]);
}
}

Related

NSPredicate limit results

I am trying to limit array of objects getting with [NSArray filteredArrayUsingPredicate] for better performance.
My Code:
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF.Name contains[c] %#", searchText];
NSArray *filteredArray = [self.dataArray filteredArrayUsingPredicate:predicate];
My dataArray contains about 30.000 objects and I want to limit result array 50. (I need some break statement after 50 match found.) How can I achieve this?
Use simple for-in loop, NSMutableArray builder and -[NSPredicate evaluateWithObject:] method.
NSMutableArray *builder = [NSMutableArray arrayWithCapacity:50];
for (id object in array) {
if ([predicate evaluateWithObject:object]) {
[builder addObject:object];
if (builder.count >= 50) break;
}
}
I noticed you tagged the question by Core Data. If you can use NSFetchRequest, then just set its fetchLimit to 50.
How about this?
myArray = [originalArray filteredArrayUsingPredicate:myPredicate];
if ([myArray count] > resultLimit) {
myArray = [myArray subarrayWithRange:NSMakeRange(0, resultLimit)];
}

Check two NSArrays for containing each other's objects (NSManagedObject)

I'm stuck at following problem for quite some time now:
I've got two NSArrays, both containing NSManagedObject subclass-objects.
They're fed by different sources but the objects in them still have the same properties/values.
What I want to do now is check if array A contains objects from array B and vice versa.
Unfortunately NSArray's containsObject-method doesn't seem to work here.
I think it uses id-testing for the equality check on each object, doesn't it?
So, does anybody have a clue, what to try?
I even tried to encapsulate my objects in NSSets, using member: as my comparison-method but this didn't work out as well, especially because "you must not override" isEqual etc. for NSManagedObject subclasses.
Here's a code snippet:
//manufacturers is an array, parsed out of some xml here...
for(Manufacturer *manu in [fetchedResultsController fetchedObjects])
{
if(![manufacturers containsObject:manu])
{
NSLog(#"Deleting %#", manu.name);
[self.mContext deleteObject:manu];
}
}
for(Manufacturer *manu in manufacturers)
{
if(![[fetchedResultsController fetchedObjects] containsObject:manu])
{
NSLog(#"Adding %#", manu.name);
[newArray addObject:manu];
}
}
Thanks in advance for any hint ;)
I'm not sure if this works, but you could try to match the dictionaries you get with dictionaryWithValuesForKeys:.
Something like this:
NSArray *keysToCompare = [NSArray arrayWithObjects:#"FooAttribute", #"BarAttribute", nil];
// create an array with the dictionary representation of the managedObject
NSMutableArray *fetchedObjectsDictionaries = [NSMutableArray arrayWithCapacity:[[fetchedResultsController fetchedObjects] count]];
for (NSManagedObject *object in [fetchedResultsController fetchedObjects]) {
NSDictionary *dictionaryRepresentation = [object dictionaryWithValuesForKeys:keysToCompare];
[fetchedObjectsDictionaries addObject:dictionaryRepresentation];
}
// another array with dictionaries for managedObjects
NSMutableArray *manufacturersDictionaries = [NSMutableArray arrayWithCapacity:[manufacturers count]];
for (NSManagedObject *object in manufacturers) {
NSDictionary *dictionaryRepresentation = [object dictionaryWithValuesForKeys:keysToCompare];
[manufacturersDictionaries addObject:dictionaryRepresentation];
}
// compare those dictionaries
for (NSInteger i = 0; i < [fetchedObjectsDictionaries count]; i++) {
NSDictionary *dictionary = [fetchedObjectsDictionaries objectAtIndex:i];
if (![manufacturersDictionaries containsObject:dictionary]) {
// get the corresponding managedObject
NSManagedObject *object = [[fetchedResultsController fetchedObjects] objectAtIndex:i];
[newArray addObject:object];
}
}
if that won't work you can write your own isEqualToManufacturer: method and enumerate trough the arrays manually.
There would be 3 types of equality you can check for: same memory address, managed object id equality, and value equality. Your current code already checks to see if the objects share the same memory address and this is most likely not what you are interested in. This leaves two possible options. Using the managed object id equality method you can check if the manufacturers point to the same row in the database. Using the value equality you can check if two manufacturers are equal based on the shared values. Below is a way to check for NSManagedObjectID equality.
for(Manufacturer *manu in [fetchedResultsController fetchedObjects])
{
id databaseIDTest = ^(Manufacturer * checkManu, NSUInteger idx, BOOL *stop){
return [[checkManu objectID] isEqual:[manu objectID]];
};
if([manufacturers indexOfObjectPassingTest:databaseIDTest] == NSIndexNotFound)
{
NSLog(#"Deleting %#", manu.name);
[self.mContext deleteObject:manu];
}
}
for(Manufacturer *manu in manufacturers)
{
id databaseIDTest = ^(Manufacturer * checkManu, NSUInteger idx, BOOL *stop){
return [[checkManu objectID] isEqual:[manu objectID]];
};
NSArray * fetchedObjects = [fetchedResultsController fetchedObjects];
if([fetchedObjects indexOfObjectPassingTest:databaseIDTest] == NSIndexNotFound)
{
NSLog(#"Adding %#", manu.name);
[newArray addObject:manu];
}
}
You need to override -isEqual: since that's what -[NSArray containsObject:] calls into:
- (BOOL)isEqual:(id)other;
{
if (![other isKindOfClass:[Manufacturer class]]) {
return NO;
}
Manufacturer *otherManufacturer = other;
return ([self.name isEqual:otherManufacturer.name] &&
...
);
}
Checking for containment inside an NSSet is cheaper (and may make sense if you run into performance problems). It only works if you have a relatively decent -hash implementation, but it's easy to implement like this:
- (NSUInteger)hash;
{
return [self.name hash] + [self.foo hash] + ...;
}
Don't go trough too much trouble with the hash, just use 2 - 3 values that are most likely to uniquely identify the object.

Error spliting NSarray into sections

Okay so I have been working through an example that closely matches what I am trying to achive, the sole difference being that in the example he is directly calling from his database the data he needs to be sectioned etc. Where as I already have a sorted NSArray.
This is the tutorial I am working off - iPhone Development: Creating Native Contacts like screen
I have created a Method that is capturing each entry in the NSArray and putting these results into a alpha based NSDictionary (so their will be a NSDictionary for A,B,C... etc)
here is my method.
//method to sort array and split for use with uitableview Index
- (IBAction)startSortingTheArray:(NSMutableArray *)arrayData
{
//Sort incoming array alphabetically
//sortedArray = [arrayData sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
[self setSortedArray:[arrayData sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)]];
arrayOfCharacters = [[NSMutableArray alloc]init];
objectsForCharacters = [[NSMutableDictionary alloc]init];
for(char c='A';c<='Z';c++)
{
if([sortedArray count] >0)
{
[arrayOfCharacters addObject:[NSString stringWithFormat:#"%c",c]];
[objectsForCharacters setObject:sortedArray forKey:[NSString stringWithFormat:#"%c",c]];
NSLog(#"%#", objectsForCharacters);
}
[sortedArray release];
//Reloads data in table
[self.tableView reloadData];
}
}
This is putting every value into every alpha section, I am hoping someone can help me with making it so that only alpha sections are established if there is a value in the array for it.. then only loading those values into each section, not every section.
This piece of code will do just that and will be much more efficient than filtering the array once for each letter.
//Sort incoming array alphabetically so that each sub-array will also be sorted.
NSArray *sortedArray = [arrayData sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
// Dictionary will hold our sub-arrays
NSMutableDictionary *arraysByLetter = [NSMutableDictionary dictionary];
// Iterate over all the values in our sorted array
for (NSString *value in sortedArray) {
// Get the first letter and its associated array from the dictionary.
// If the dictionary does not exist create one and associate it with the letter.
NSString *firstLetter = [value substringWithRange:NSMakeRange(0, 1)];
NSMutableArray *arrayForLetter = [arraysByLetter objectForKey:firstLetter];
if (arrayForLetter == nil) {
arrayForLetter = [NSMutableArray array];
[arraysByLetter setObject:arrayForLetter forKey:firstLetter];
}
// Add the value to the array for this letter
[arrayForLetter addObject:value];
}
// arraysByLetter will contain the result you expect
NSLog(#"Dictionary: %#", arraysByLetter);
Note that arraysByLetter is a dictionary that contains one array per "first letter" that exists in your initial data.
--- Added on 2011-09-23 ---
[sortedArray removeAllObjects];
NSArray *sortedKeys = [arraysByLetter.allKeys sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
for (NSString *key in sortedKeys) {
[sortedArray addObject:key];
[sortedArray addObjectsFromArray: [arraysByLetter objectForKey:key]];
}
NSLog(#"Sorted Array: %#", sortedArray);
The output is the following:
C,
Computer,
H,
Helene,
Hello,
J,
Jules,
W,
World
Looks like you need to filter sortedArray with a predicate for each letter. Something like this...
for(char c='A';c<='Z';c++) {
NSPredicate *predicate =
[NSPredicate predicateWithFormat:#"SELF beginswith[c] '%c'", c];
NSArray *objectsBeginningWithCurrentLetter = [array filteredArrayUsingPredicate:predicate];
if([sortedArray count] >0)
{
[arrayOfCharacters addObject:[NSString stringWithFormat:#"%c",c]];
if ([objectsBeginningWithCurrentLetter count] > 0) {
[objectsForCharacters setObject:objectsBeginningWithCurrentLetter forKey:[NSString stringWithFormat:#"%c",c]];
NSLog(#"%#", objectsForCharacters);
}
}
[sortedArray release];
//Reloads data in table
[self.tableView reloadData];
}

Search NSArray for value matching value

I have an NSArray of objects, which has a particular property called name (type NSString).
I have a second NSArray of NSStrings which are names.
I'd like to get an NSArray of all the objects whose .name property matches one of the names in the second NSArray.
How do I go about this, fast and efficiently as this will be required quite often.
Why not just to use predicates to do that for you?:
// For number kind of values:
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF = %#", value];
NSArray *results = [array_to_search filteredArrayUsingPredicate:predicate];
// For string kind of values:
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF contains[cd] %#", value];
NSArray *results = [array_to_search filteredArrayUsingPredicate:predicate];
// For any object kind of value (yes, you can search objects also):
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", value];
NSArray *results = [array_to_search filteredArrayUsingPredicate:predicate];
Here's a simple way:
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"name == %#", nameToFind];
[listOfItems filteredArrayUsingPredicate:predicate];
With your current data structures, you can only do it in O(n^2) time by looping over the first array once for each member of the second array:
NSMutableArray * array = [NSMutableArray array];
for (NSString * name in names) {
for (MyObject * object in objects) {
if ([[myObject name] isEqualToString:name]) {
[array addObject:object];
}
}
}
(Alternate as suggested by Stefan: loop over the objects array and ask the names array if it containsObject: for the name of each object.)
But if this really needs to be faster (really depends on the size of the arrays as much as how often you do it), you can improve this by introducing an NSDictionary that maps the names in the first array to their objects. Then each of those lookups is O(1) and the overall time is O(n). (You'd have to keep this dictionary always in sync with the array of objects, which isn't hard with reasonable accessors. This technique also has the constraint that the same name can't appear on more than one object.)
An alternate way of getting this result (and which doesn't have that last constraint) is to use an NSSet for your second collection, then walk through the objects array calling containsObject: with each one on the set of names. Whether this technique is better depends on whether your two collections are roughly the same size, or if one is much larger than the other.
I like to use this method:
NSIndexSet *indexes = [_items indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
return ((MyObject *)obj).name isEqualToString:name];
}];
if (indexes.count != 0) {
//extract your objects from the indexSet, and do what you like...
}
NSMutableArray * foundNames = [NSMutableArray array];
for (MyObject * objectWithName in objectCollection) {
if ([names containsObject:objectWithName.name]) {
[foundNames objectWithName];
}
}
The methods most helpful will be:
filteredArrayUsingPredicate:
and
indexesOfObjectsPassingTest:
The second one uses a code block, not available on iOS before 4.0
Both of these will be more efficient than iterating directly.
There's a good example here:
http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/Blocks/Articles/bxUsing.html
NSMutableArray* solutions = [NSMutableArray array];
for (Object* object in objects){
for (NSString* name in names){
if ([object.name isEqualToString:name]){
[solutions addObject:object];
break; // If this doesnt work remove this
}
}
}
int count=0;
if (range.location!=NSNotFound)
{
[searchindex addObject:[NSString stringWithFormat:#"%d",count]];
}

How to check if the value in an NSDictionary exists in an array of dictionarys

The title is a bit confusing...I'll explain
I have an NSMutableArray I am populating with NSMutableDictionary objects. What I am trying to do is before the dictionary object is added to the array, I need to check whether any of the dictionaries contain a value equal to an id that is already set.
Example:
Step 1: A button is clicked setting the id of an object for use in establishing a view.
Step 2: Another button is pressed inside said view to save some of its contents into a dictionary, then add said dictionary to an array. But if the established ID already exists as a value to one of the dictionaries keys, do not insert this dictionary.
Here is some code I have that is currently not working:
-(IBAction)addToFavorites:(id)sender{
NSMutableDictionary *fav = [[NSMutableDictionary alloc] init];
[fav setObject:[NSNumber numberWithInt:anObject.anId] forKey:#"id"];
[fav setObject:#"w" forKey:#"cat"];
if ([dataManager.anArray count]==0) { //Nothing exists, so just add it
[dataManager.anArray addObject:fav];
}else {
for (int i=0; i<[dataManager.anArray count]; i++) {
if (![[[dataManager.anArray objectAtIndex:i] objectForKey:#"id"] isEqualToNumber:[NSNumber numberWithInt:anObject.anId]]) {
[dataManager.anArray addObject:fav];
}
}
}
[fav release];
}
One fairly easy way to do this kind of check is to filter the array using an NSPredicate. If there's no match, the result of filtering will be an empty array. So for example:
NSArray *objs = [dataManager anArray];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"id == %#", [NSNumber numberWithInt:i]];
NSArray *matchingObjs = [objs filteredArrayUsingPredicate:predicate];
if ([matchingObjs count] == 0)
{
NSLog(#"No match");
}