NSArray, how get items based on a property's value [duplicate] - ios

This question already has answers here:
Filter NSArray of custom objects
(3 answers)
Closed 9 years ago.
I have NSMutableArray which contains a list of people , now I need to get a list of all people where gender = male, how can I do that? should I get into NSPredicates to do that?

Copy this NSArray category to to somewhere in your code
#implementation NSArray (My)
-(NSArray*)arrayWithPredicate:(BOOL(^)(id obj))predicate {
NSMutableArray* objs = [NSMutableArray array];
[self enumerateObjectsUsingBlock:^(id o, NSUInteger idx, BOOL *stop) {
if (predicate(o)) {
[objs addObject:o];
}
}];
return objs;
}
#end
Then where you need to get the male ones:
NSArray* males = [people arrayWithPredicate:^BOOL(id obj) {
// Gender check
}];
The advantage over NSPredicate is that you don't have to use a literal string to specify the criteria (quite a mess if the criteria is complex).

yes you can use like this,
NSArray *filtered = [data filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"self.gender == %#", #"male"]];
NSLog(#"%#",filtered);

Related

iOS: sorting an NSArray of core data objects [duplicate]

This question already has answers here:
How do I sort an NSMutableArray with custom objects in it?
(27 answers)
Closed 8 years ago.
I have a NSArray with core data entities called:
"Struct"
thy have an attribute called "value" that can be a double
Struct *struct = [array objectAtIndex:0];
double val = [struct value];
I have to sorting this array by this value but I don't understand what's the way to do it, because I have not a key to access to the object.
Do you have any suggests?
NSMutableArray *sortedArray;
sortedArray = [array sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
NSNumber *s1 = #([(Struct *)a value]);
NSNumber *s2 = #([(Struct *)b value]);
return [s1 compare:s2];
}];

Easy way to search array of dictionary [duplicate]

This question already has answers here:
How to implement searching of a string in an array of dictionaries?
(2 answers)
Searching NSArray of NSDictionary objects
(3 answers)
Closed 8 years ago.
I have a NSArray looking like:
[{#"firstName":#"abc", #"lastName":#"ABC"},
...
{#"firstName":#"xyz", #"lastName":#"XYZ"}]
I want to get the dictionary element in which lastName=XYZ, that is, the array element:
{#"firstName":#"xyz", #"lastName":#"XYZ"}
is there an easy way to get it without a lot of loops? Thanks.
NSArray *people = ...;
NSUInteger chosenIndex = [people indexOfObjectPassingTest:^(id obj, NSUInteger idx, BOOL *stop) {
NSDictionary *person = obj;
return [person[#"lastName"] isEqualToString:#"XYZ"];
}];
if (chosenIndex != NSNotFound) {
NSDictionary *chosenPerson = people[chosenIndex];
NSLog(#"I chose %#", chosenPerson);
}

sort an NSMutableArray that contains NSString objects [duplicate]

This question already has answers here:
How to sort a NSArray alphabetically?
(7 answers)
Closed 9 years ago.
I am new to objective-c, ios.
I'm trying to sort in alfabetic order a NSMutableArray called filteredList that contains objects of type NSString.
so if my mutable array contains : [Mary, Bill, John] I would like to have [Bill, Mary, John]
I did the following:
[filteredList sortUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
but I do not see any change. I did read and tried other solutions like compare: instead of localizedCaseInsensitiveCompare but still nothing.
Updated
NSArray *sortedArray =[unSortedArray sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];//unSortedArray is NSMutableArray
unSortedArray = [[NSMutableArray alloc]initWithArray:sortedArray];
I would do something like:
NSArray *sortedArray = [filteredList sortedArrayUsingComparator:^(NSString *str1, NSString *str2) {
return (NSComparisonResult)[str1 compare:str2];
}];
filteredList = [sortedArray mutableCopy];
Please refer the below code:-
filteredList = (NSMutableArray*)[filteredList sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];

Sort NSArray of NSStrings based on a super set of ordered Strings

I have an NSArray which contains some NSString objects. For example:
NSArray *objects = #[#"Stin",#"Foo",#"Ray",#"Space"];
Now I need to sort this array based on following order of Strings.
NSArray *sortOrder = #[#"John",#"Foo",#"Space",#"Star",#"Ray",#"Stin"];
So the answer should be
NSArray *sorted = #[#"Foo",#"Space",#"Ray",#"Stin"];
How can I achieve this?
ANSWER:
Based on Accepted answer of dasblinkenlight, I did following and it worked to charm.
NSMutableArray *objects = #[#"Star",#"Stin",#"Foo",#"Ray",#"Space",#"John"];
NSArray *sortOrder = #[#"John",#"Foo",#"Space",#"Star",#"Ray",#"Stin"];
[objects sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
int index1 = [sortOrder indexOfObject:obj1];
int index2 = [sortOrder indexOfObject:obj2];
if (index1 > index2)
return NSOrderedDescending;
if (index1 < index2)
return NSOrderedAscending;
return NSOrderedSame;
}];
Create NSComparator that holds a reference to the superset array, and decides the relative order of strings by comparing the results of calling [superset indexOfObject:str] on both strings. Call sortedArrayUsingComparator: passing an instance of NSComparator to get the desired ordering.
dasblinkenlight's solution would work, but like most programming problems there are multiple ways to go about it. Here is one such alternative:
NSMutableArray *sorted = [NSMutableArray arrayWithCapacity:0];
[sortOrder enumerateObjectsUsingBlock:^(NSString *sortedString, NSUInteger idx, BOOL *stop) {
if ([objects containsObject:sortedString]) {
[sorted addObject:sortedString];
}
}];
The variable names correspond to the variable names used in the original question.
This works because the enumeration happens in order. Therefore, what takes place is, essentially, a cull of the objects that exist in both arrays in the order as specified by sortOrder.

NSPredicate check NSArray if object has one of several ID

Little diifficult to explain but I am trying to use NSPredicate for filtering an array with custom NSManagedObject by ids. I have a server that can send update, delete or add new objects, and I need to control if those objects from the JSON file already exist, if exist just update them or insert to core data if not.
I am using this predicate now :
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"storeId != %#", [jsonFile valueForKey:#"Id"];
Where jsonFile contains unparsed Store objects. But with this predicate, it will give me a huge array, since one id will be unlike some storeId, and next id will match.
Json file is some sort of this :
"Stores":[{
"id":1,
"name":"Spar",
"city":"London"
}
{
"id":2,
"name":"WalMart",
"city":"Chicago"
}];
I am not sure if I understand correctly what you are trying to achieve, but perhaps you can use the following:
NSArray *jsonFile = /* your array of dictionaries */;
NSArray *idList = [jsonFile valueForKey:#"id"]; // array of "id" numbers
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"NOT(storeId IN %#)", idList];
This will give all managed objects that have a storeId that is not equal to any of the ids in the jsonFile array.
The syntax of the predicate is probably off - someone else may suggest a fix - but if you have an array, why not use
- (NSUInteger)indexOfObjectPassingTest:(BOOL (^)(id obj, NSUInteger idx, BOOL *stop))predicate
since its much easier:
NSInteger textID = ... // you set this
NSInteger idx = [myArray indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop))
{
NSInteger objIdx = [obj objectForKey:#"id"] integerValue]; // integerValue works for both NSNUmbers and NSStrings
if(objIdx == testID) {
return YES;
*stop = YES;
}
}

Resources