In my app, I have a UITableView that is currently set to show everything inside the Downloads folder that is a PDF. What I'd like to do is have it show everything UNLESS it contains a specific word. I know I can use NSPredicate to make an NSArray that ONLY has that word, but how can I do the opposite? I've tried making it an NSMutableArray and then looping through it to remove all objects that contain that word, but it isn't working.
NSArray *theNewArray22 = [thefirstNewArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"self ENDSWITH 'Kids.pdf'"]];
NSMutableArray *arr = [NSMutableArray arrayWithArray:theNewArray22];
for (int i = 0 ; i< arr.count; i++) {
[arr removeObjectAtIndex:i];
}
NSArray *resultArr = [arr mutableCopy];
I was thinking that since the predicate should return ONLY those that end with Kids.pdf, that looping through it to remove each object would work, but for some reason I can't get it.
Related
I got following response from server:
[{"bp":"000/000","dateTime":"05/12/2016 01:02:59 PM","doc":{"email_id":"batra#gmail.com","exception":0,"gender":"Male","id":0,"mobile_no":8055621745,"name":"Batra","profile_id":0,"qualification":"MD(Doctor)","reg_id":157,"salutation":"Mr","wellness_id":"251215782521"},"follow_up":"17","id":37,"medicine":["Syrup,Decold Total,20,0-0-1,Before Meal,1","Injection,Insulin,1,0-0-1,Before Meal,1","no","no","no","no","no","no","no","no"],"patient":{"email_id":"bishtrohit1989#gmail.com","exception":0,"gender":"Male","id":0,"mobile_no":8055621745,"name":"Rohit","profile_id":0,"qualification":"","reg_id":150,"salutation":"Mr","wellness_id":"290119935030"},"weight":"000"}]
From that I have separate the medicine array like following way:
NSMutableArray *Myarray = [NSMutableArray new];
for (int i=0; i<_menuItems.count; i++) {
[Myarray addObject:[[_menuItems objectAtIndex:i] objectForKey:#"medicine"]];
NSLog(#"medicine: %#",Myarray);
I got output for this as like:
medicine: (
(
"Syrup,Decold Total,20,0-0-1,Before Meal,1",
"Injection,Insulin,1,0-0-1,Before Meal,1",
no,
no,
no,
no,
no,
no,
no,
no
)
)
Now what i want:
1) remove that all noelement.
2) after that, i want only 2nd element in each string.
in short i want my final output is like:
[Decold Total, Insulin];
But i don't know how to do that..??
Please anyone can solve my issue. help will be appreciable.
You need to use NSPredicate on Myarray and filter it.
Make your Myarray like this.
NSMutableArray *Myarray = [NSMutableArray new];
for (int i=0; i<_menuItems.count; i++) {
[Myarray addObjectsFromArray:[[_menuItems objectAtIndex:i] objectForKey:#"medicine"]];
}
1) Remove that all no element.
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"NOT (SELF = %#)",#"no"];
NSArray *filterArray = [Myarray filteredArrayUsingPredicate:predicate];
2) Want only 2nd element in each string
NSMutableArray *medicineArray = [[NSMutableArray alloc] init];
for (NSString* medicine in filterArray) {
NSArray *arr = [medicine componentsSeparatedByString:#","];
if (arr.count >= 2) {
[medicineArray addObject:[arr objectAtIndex:1]];
}
}
I have a tableview that i want to search through with a searchable. It worked before but when i added sections i got into trouble because i had to change from arrays to dictionary.
So basically i have a NSDictionary that looks like this
{ #"districtA": array with point objects, #"districtB": array with point objects}
I need to filter them based on the point objects.name that is in the arrays. After that i want to create a new nsdictionary with the filtered objects in it.
I tried at least 10 different methods but i can't figure it out so i think this is the only way that i am most positive that should work.
This is the only way i can think of if there is an easier way or more logic way please tell me.
-(void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope {
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF.name BEGINSWITH[c] %#",searchText];
//create new array to fill
NSArray *arrayWithFilteredPoints = [[NSArray alloc] init];
//loop through the values and put into an rray based on the predicate
arrayWithFilteredPoints = [NSArray arrayWithObject:[[self.PointList allValues] filteredArrayUsingPredicate:predicate]];
NSMutableDictionary *dict = [#{} mutableCopy];
for (Point *point in arrayWithFilteredPoints) {
if (![dict objectForKey:Point.district])
dict[Point.district] = [#[] mutableCopy];
[dict[Point.district]addObject:Point];
}
self.filteredPointList = dict;
self.filteredDistrictSectionNames = [[dict allKeys] sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];}
This results in a crash, it happens of course where the predicate is used but i don't know how to debug what predicate i should use:
on 'NSInvalidArgumentException', reason: 'Can't do a substring operation with something that isn't a string (lhs = (
West ) rhs = w)'
I have read the comments and you are right. There was something wrong with my code.
I changed the logic, i added some more steps (like creating NSArray without needing it) to make the solution clear
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF.name BEGINSWITH[c] %#",searchText];
//1. create new array to fill only the Points from the dictionary
NSArray *allPoints = [self.PointList allValues];
NSMutableArray *allPointObjects = [[NSMutableArray alloc]init];
for (NSArray *array in allPoints) {
for (Point *point in array) {
[allPointObjects addObject:point];
}
}
//2. loop through allPointObjects and put into an mutablearray based on the predicate
NSArray *arrayWithFilteredPoints = [[NSArray alloc] init];
arrayWithFilteredPoints = [allPointObjects filteredArrayUsingPredicate:predicate];
NSMutableDictionary *dict = [#{} mutableCopy];
for (Point *point in arrayWithFilteredPoints) {
if (![dict objectForKey:point.district])
dict[point.district] = [#[] mutableCopy];
[dict[point.district]addObject:Point];
}
self.filteredPointList = dict;
self.filteredDistrictSectionNames = [[dict allKeys] sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
I wanted a filtered nsdictionary at the end that i can pass back to my tableview that reads the dictionary objects based on the keys (districts)
It seems clear from your description that [self.PointList allValues] is not an array of Point objects but an array of arrays of Point objects. That is the source of your difficulty, including your original crash.
You need to decide what to do about that; for example, if you want just one big array of Point objects, then flatten the array of arrays before you filter. I can't advise you further because it is not obvious to me what ultimate outcome you desire.
EDIT You've now modified your code and I can see more clearly what you're trying to do. You have a dictionary whose values are arrays of points, and you are trying to filter some of the points out of each array. What I would have done is to do that - i.e., run thru the keys, extract each array, filter it, and put it back (or delete the key if the array is now empty). But I can see that what you are doing should work, because you have cleverly put the keys into the points to start with, so you can reconstruct the dictionary structure from that.
I need help with the following:
I have an NSArray with NSStrings, I want to loop thru these strings and find a matching string, when match is found the strings after this match will be extracted into an NSDictionary until a certain other match is hit.
Here is an example:
NSArray *array = #[#"Fruit",#"Apple",#"Vegtable",#"Tomato",#"Fruit",#"Banana",#"Vegtable",#"Cucumber"];
So I want to loop thru this array and split it in 2 arrays one for fruit and one for vegetable.
Anyone can help with the logic?
Thanks
This is probably the simplest way to solve the problem:
NSArray *array = #[#"Chair",#"Fruit",#"Apple",#"Orange",#"Vegetable",#"Tomato",#"Fruit",#"Banana",#"Vegetable",#"Cucumber"];
NSMutableArray *fruitArray = [NSMutableArray array];
NSMutableArray *vegetableArray = [NSMutableArray array];
NSMutableArray *currentTarget = nil;
for (NSString *item in array)
{
if ([item isEqualToString: #"Fruit"])
{
currentTarget = fruitArray;
}
else if ([item isEqualToString: #"Vegetable"])
{
currentTarget = vegetableArray;
}
else
{
[currentTarget addObject: item];
}
}
In one iteration over the array, you just keep adding items to a result array using a pointer to one of two result arrays according to the last occurrence of the #"Fruit" or #"Vegetable" string.
This algorithm ignores all items before the first occurrence of the #"Fruit" or #"Vegetable" string, because the currentTarget is initialized to nil, which ignores the addObject: messages. If you want different behaviour, just change the initialization.
You said you wanted the results in a NSDictionary, but didn't specify what should be the key. If you want one NSDictionary with two keys, Fruit and Vegetable, and values NSArrays containing the items, just use the arrays previously created:
NSDictionary *dict = #{ #"Fruit": fruitArray, #"Vegetable": vegetableArray };
PS: You have a typo in your example, Vegtable instead of Vegetable. I corrected it in my code, so keep it in mind.
If I completely understand you:
NSArray *array = #[#"Fruit",#"Apple",#"Vegtable",#"Tomato",#"Fruit",#"Banana",#"Vegtable",#"Cucumber"];
NSMutableArray *fruits = [NSMutableArray array];
NSMutableArray *vegtables = [NSMutableArray array];
for (NSInteger i = 0; i < array.count; ++i){
if ([array[i] isEqualToString:#"Fruit"]){
++i;
[fruits addObject:array[i]];
}
else if ([array[i] isEqualToString:#"Vegtable"]){
++i;
[vegtables addObject:array[i]];
}
}
I am creating an NSArray of NSStrings, however one of the arrays that is entered is a set of quotation marks:
""
I would like to know hot to exclude these from my array, I have tried using a predicate but it's not working.
This is what my code looks like:
NSString *tempSymbolsString = [tempAxesDictionary objectForKey:#"Symbols"];
NSArray *tempSymbolsArray = [tempSymbolsString componentsSeparatedByString:#";"];
tempSymbolsArray = [symbolsArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"SELF != """""]];
NSLog(#"%#", tempSymbolsArray);
Actually is even simpler than this. Since you only got strings in your array, create a mutable copy and remove all occurrences of "". Something like this perhaps:
NSMutableArray *temp = [tempSymbolsArray mutableCopy];
[temp removeObject:#"\"\""];
This works since removeObject: will compare objects via isEqual: and remove any matches.
Do it yourself:
NSString *tempSymbolsString = tempAxesDictionary[#"Symbols"];
NSMutableArray *symbolsArray = [[tempSymbolsString componentsSeparatedByString:#";"] mutableCopy];
for (NSUInteger i = symbolsArray.count; i > 0; i--) {
if ([symbolsArray[i - 1] isEqualToString:#"\"\""]) {
[symbolsArray removeObjectAtIndex:i - 1];
}
}
At the end the symbolsArray will have all values except those matching "".
BTW - your original predicate probably needs a bunch of escaping:
[NSPredicate predicateWithFormat:#"SELF != \"\\\"\\\"\""]
I have an array of recommendedcar IDs, and another array of allcar IDs. From this, I have to take the recommendedcar images. First, I check whether the recommended carid is in my allcar id; if it is, I select the corresponding car images, and store them into NSArray.
This is the code I am using.
for (int i=0;i<[listOfCarId count];i++) {
for (int j=0;j<[_allCarID count];j++) {
tempAllCarId=[_allCarID objectAtIndex:j];
tempRecommendedCarId=[listOfCarId objectAtIndex:i];
if ([tempRecommendedCarId isEqualToString:tempAllCarId]) {
_recommendedCarImage=[_allCarImages objectAtIndex:j];
NSLog(#"finalImage%#",_recommendedCarImage);
}
}
}
_recommendedcarImage is NSMUtableArray; I want a NSArray. How can I convert it to a NSArray?
How can i replace the "_recommendedCarImage " with an NSArray?? Currently _recommendedCarImage is a mutable array.
Polymorphism. Since NSMutableArray is a subclass of NSArray, you can use it anywhere an NSArray is expected. You don't have to do anything.
Now its working,What i did is , I just copy the contents of Mutable array to NSarray
recommendedArray=[_recommendedCarImage copy];
An NSMutableArray is an NSArray already (as it's a subclass of NSArray), still you can do:
NSArray *array = [NSArray arrayWithArray:mutableArray];