how to remove NULL values from NSMutableArray? ios - iphone

i have array of birthdates as array is getting filled from facebook so there are some friends whos birthdates are private so it contain NULL how to convert that array like empty string wherever there is null value the array is like below
"<null>",
"10/29/1988",
"11/13",
"03/24/1987",
"04/25/1990",
"03/13",
"01/01",
"<null>",
"12/15/1905",
"07/10",
"11/02/1990",
"12/30/1990",
"<null>",
"07/22/1990",
"01/01",
"07/17/1989",
"08/28/1990",
"01/10/1990",
"06/12/1990",

The null values appear to be string literals #"<null>" rather than the NSNull objects typically used to represent nils in Cocoa collections. You can filter them out by using NSArray's filteredArrayUsingPredicate method:
NSArray *filtered = [original filteredArrayUsingPredicate:pred];
There are several ways of making the pred, one of them is
NSPredicate *pred = [NSPredicate predicateWithBlock:^BOOL(id str, NSDictionary *unused) {
return ![str isEqualToString:#"<null>"];
}];

You have to use this to remove the actual [NSNull null] value.
[array removeObjectIdenticalTo:[NSNull null]];

This works for me:
NSMutableArray *array = [NSMutableArray arrayWithObjects:
#"<null>",
#"10/29/1988",
#"11/13",
#"03/24/1987",
#"04/25/1990",
#"03/13",
#"01/01",
#"<null>",
#"12/15/1905",
#"07/10",
#"11/02/1990",
#"12/30/1990",
#"<null>",
#"07/22/1990",
#"01/01",
#"07/17/1989",
#"08/28/1990",
#"01/10/1990",
#"06/12/1990", nil];
NSLog(#"%d", [array count]);
NSString *nullStr = #"<null>";
[array removeObject:nullStr];
NSLog(#"%d", [array count]);

In order to remove null values use :
[yourMutableArray removeObjectIdenticalTo:[NSNull null]];
You don't need iterate over.

for(int i = 0;[yourMutableArray count] > 0;i++){
if([yourMutableArray isKindOfClass:[NSNull class]]){ // indentifies and removes null values from mutable array
[yourMutableArray removeObjectAtIndex:i];
// or
[yourMutableArray replaceObjectAtIndex:i withObject:#"No date available"];
NSLog(#"*** %#",yourMutableArray);
}
}

For json response I removed null values like this
NSArray *arr = [NSArray arrayWithObjects:_IDArray, _TypeArray, _NameArray, _FlagArray, nil];
for (int i=0; i<_integer; i++) {
// My json response assigned to above 4 arrayes
//Now remove null values
//Remove null values
for (int j=0; j<arr.count; j++) {
for (NSMutableArray *ar in arr) {
if ([[ar objectAtIndex:i] isKindOfClass:[NSNull class]] || [[ar objectAtIndex:i] isEqualToString:#"null"]) {
[ar addObject:#""];//Add empty value before remove null value
[ar removeObjectAtIndex:i];
}
}
}
}
Now remove empty values
//Add arrays to mutable array to remove empty objects
NSArray *marr = [NSArray arrayWithObjects:_IDArray, _TypeArray, _NameArray, _FlagArray, nil];
//Remove empty objects from all arrays
for (int j=0; j<marr.count; j++) {
for (int i=0; i<[[marr objectAtIndex:j] count]; i++) {
if ([[[marr objectAtIndex:j] objectAtIndex:i] isEqualToString:#""]) {
[[marr objectAtIndex:j] removeObjectAtIndex:i];
}
}
}

Related

Remove certain objects from NSMutableArray [duplicate]

This question already has answers here:
Removing object from NSMutableArray
(5 answers)
Closed 9 years ago.
I have an NSMutableArray of objects which are of AdDetail class that hold a few properties (for eg. adId, adTitle, adPrice... etc). I want to remove only those objects which have adID = 0. How can I do that ?
Perhaps something more elegant would suffice?
[array removeObjectsInArray:[array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"adID == 0"]]];
Using predicate
NSArray *filtered=[array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"(adId == 0)"]];
Using fastEnumeration:
NSMutableArray *newArray=[NSMutableArray new];
for(AdDetail adDetailObj in array){
if(![[adDetailObj adId] isEqualToString:#"0"]){ //if these are strings, if NSInteger then directly compare using ==
newArray[newArray.count]=adDetailObj;
}
}
Now newArray contains all objects other than id=0
Use following code :
int count = array.count;
for(i=0;i<count;i++){
ADetail *adetail = [array objectAtIndex:i];
if(adetail.adID = 0){
[array removeObjectAtIndex:i];
i--;
}
count = array.count;
}
NSMutableArray *newArray = [NSMutableArray arrayWithArray:yourArray];
for (int i = 0; i < yourArray.count; i++)
{
AdDetail *obj = (AdDetail *)[yourArray objectAtIndex:i];
if (obj.adID == 0)
[newArray removeObjectAtIndex:i];
}
yourArray = [newArray mutableCopy];
for(i=0; i < myArray.count; i++)
{
myClass = [myArray objectAtIndex:i];
if([myClass.adID isEqualtoString:"0"])// if it it int/NSInteger the write myClass.adID==0
{
[myArray removeObjectAtIndex:i];
i--;
}
}
predicate = #"adID == 0";
newArray = [theArray filterUsingPredicate:aPredicate]

Search String into NSArray based on charcters order?

My Problem Scenario is like this. I have an NSMutableArray ( Every Object is Nsstring). I have a UItextField ( as Client said) for Search.
I want know how to Search String into NSMutableArray like this
if I type A into textfield only those Content come from NSMutableArray which start From A.
if I type AB into TextField only those Content Comes from NSMutableArray which is started from AB..
....
I am Trying NSRange Concept I like share Mycode
~
for (int i=0; i<[[localTotalArrayForAwailable objectForKey:#"PUNCH"] count]; i++)
{
NSString *drinkNamePuch= [[[localTotalArrayForAwailable objectForKey:#"PUNCH"] objectAtIndex:i] drinkNames];
NSRange titleResultsRange = [drinkNamePuch rangeOfString:searchText options:( NSCaseInsensitiveSearch)];
if (titleResultsRange.length>0)
{
[searchArraypuch addObject:[[localTotalArrayForAwailable objectForKey:#"PUNCH"] objectAtIndex:i]];
[copyListOfItems setValue:searchArraypuch forKey:#"PUNCH"];
}
}
~
Based on this code search not working proper as i need.
Thanks
If you're trying to find all of the strings that match your searchText from the beginning, then you should check:
if ( titleresultsRange.location == 0 )
Other than that, I am not sure what is "not working proper", you need to provide a better explanation of what your expected results are, and what your actual results are.
Do this;
NSPredicate* predicate = [NSPredicate predicateWithFormat:#"SELF BEGINSWITH[cd] %#", searchText];
NSArray* filteredStrings = [[localTotalArrayForAwailable objectForKey:#"PUNCH"] filteredArrayUsingPredicate:predicate];
In filteredStrings you got all the strings that begins with searchText.
You might find Predicate Programming Guide helpful.
try this logic....it is working
NSMutableArray *arr = [[NSMutableArray alloc]initWithObjects:#"aa",#"bbb",#"bb",#"cc",#"dd",#"ee",#"ff",#"gg",#"hh",#"ii", nil];
NSMutableArray *arrNew = [[NSMutableArray alloc]init];
NSString *strSearch = #"cccc";
int k = strSearch.length;
for (int i=0; i<[arr count]; i++) {
for (int j=0; j<k; j++) {
if (k<=[[arr objectAtIndex:i] length]) {
if ([strSearch characterAtIndex:j] != [[arr objectAtIndex:i]characterAtIndex:j]) {
break;
}
else if(j == k-1){
[arrNew addObject:[arr objectAtIndex:i]];
}
}
}
}
NSLog(#"%#",[arrNew description]);
You can use these methods, which are provided by NSArray/NSMutableArray:
In NSArray see section "Finding Objects in an Array" for filtering methods starting with "indexesOfObjects...", e.g. indexesOfObjectsPassingTest:
In NSArray see section "Deriving New Arrays" for the method filteredArrayUsingPredicate:
In NSMutableArray there is a method filterUsingPredicate:
For narrowing the results you can continue applying the filtering consecutively to the filtered arrays or index sets.
Example with indexesOfObjectsPassingTest: using a block:
NSArray *strings = [NSArray arrayWithObjects:#"A", #"a", #"aB", #"AbC", #"Bag", #"Babc", #"baCK", #"", #"dba", nil];
NSString *searchString = #"Ab";
BOOL (^startsWithPredicate)(id, NSUInteger, BOOL*) = ^BOOL (id obj, NSUInteger idx, BOOL *stop) {
NSString *string = (NSString *) obj;
NSRange range = [string rangeOfString:searchString options:NSCaseInsensitiveSearch];
return (range.location == 0);
};
NSIndexSet *indexSet = [strings indexesOfObjectsPassingTest:startsWithPredicate];
NSLog(#"Strings found: %#", [strings objectsAtIndexes:indexSet]);
Output:
Strings found: (
aB,
AbC
)

Accessing NSDictionary inside NSArray

I have an NSArray of NSDictionary.
Each dictionary in the array has three keys: 'Name', 'Sex' and 'Age'
How can I find the index in NSArray of NSDictionary where, for example, Name = 'Roger'?
On iOS 4.0 and up you can do the following:
- (NSUInteger) indexOfObjectWithName: (NSString*) name inArray: (NSArray*) array
{
return [array indexOfObjectPassingTest:
^BOOL(id dictionary, NSUInteger idx, BOOL *stop) {
return [[dictionary objectForKey: #"Name"] isEqualToString: name];
}];
}
Elegant, no?
NSUInteger count = [array count];
for (NSUInteger index = 0; index < count; index++)
{
if ([[[array objectAtIndex: index] objectForKey: #"Name"] isEqualToString: #"Roger"])
{
return index;
}
}
return NSNotFound;
If you're using iOS > 3.0 you will be able to use the for in construct.
for(NSDictionary *dict in myArray) {
if([[dict objectForKey:#"Name"] isEqualToString:#"Roger"]) {
return [myArray indexForObject:dict];
}
}
There's method [NSArray indexOfObjectPassingTest]. But it employs blocks, an Apple extension to C, and therefore is evil. Instead, do this:
NSArray *a; //Comes from somewhere...
int i;
for(i=0;i<a.count;i++)
if([[[a objectAtIndex:i] objectForKey: #"Name"] compare: #"Roger"] == 0)
return i; //That's the index you're looking for
return -1; //Not found

Problem with sorting NSDictionary

I need to sort a NSDictionary of dictionaries. It looks like:
{//dictionary
RU = "110.1"; //key and value
SG = "150.2"; //key and value
US = "50.3"; //key and value
}
Result need to be like:
{//dictionary
SG = "150.2"; //key and value
RU = "110.1"; //key and value
US = "50.3"; //key and value
}
I am trying this:
#implementation NSMutableDictionary (sorting)
-(NSMutableDictionary*)sortDictionary
{
NSArray *allKeys = [self allKeys];
NSMutableArray *allValues = [NSMutableArray array];
NSMutableArray *sortValues= [NSMutableArray array];
NSMutableArray *sortKeys= [NSMutableArray array];
for(int i=0;i<[[self allValues] count];i++)
{
[allValues addObject:[NSNumber numberWithFloat:[[[self allValues] objectAtIndex:i] floatValue]]];
}
[sortValues addObjectsFromArray:allValues];
[sortKeys addObjectsFromArray:[self allKeys]];
[sortValues sortUsingDescriptors:[NSArray arrayWithObject:[[[NSSortDescriptor alloc] initWithKey:#"floatValue" ascending:NO] autorelease]]];
for(int i=0;i<[sortValues count];i++)
{
[sortKeys replaceObjectAtIndex:i withObject:[allKeys objectAtIndex:[allValues indexOfObject:[sortValues objectAtIndex:i]]]];
[allValues replaceObjectAtIndex:[allValues indexOfObject:[sortValues objectAtIndex:i]] withObject:[NSNull null]];
}
NSLog(#"%#", sortKeys);
NSLog(#"%#", sortValues);
NSLog(#"%#", [NSMutableDictionary dictionaryWithObjects:sortValues forKeys:sortKeys]);
return [NSMutableDictionary dictionaryWithObjects:sortValues forKeys:sortKeys];
}
#end
This is the result of NSLog:
1)
{
SG,
RU,
US
}
2)
{
150.2,
110.1,
50.3
}
3)
{
RU = "110.1";
SG = "150.2";
US = "50.3";
}
Why is this happening? Can you help me with this problem?
NSDictionary are unsorted by nature. The order of the objects as retrieved by allKeys and allValues will always be undetermined. Even if you reverse engineer the order it may still change in the next system update.
There is however more powerful alternatives to allKeys that are used to retrieve the keys in a defined and predictable order:
keysSortedByValueUsingSelector: - Useful for sorting in ascending order according to the compare: method of the value objects.
keysSortedByValueUsingComparator: - New in iOS 4, use a block to do the sort inline.
WOW. Thanx, PeyloW! It's what i needed! I also find this code and it helps me to reorder results:
#implementation NSString (numericComparison)
- (NSComparisonResult) floatCompare:(NSString *) other
{
float myValue = [self floatValue];
float otherValue = [other floatValue];
if (myValue == otherValue) return NSOrderedSame;
return (myValue < otherValue ? NSOrderedAscending : NSOrderedDescending);
}
- (NSComparisonResult) intCompare:(NSString *) other
{
int myValue = [self intValue];
int otherValue = [other intValue];
if (myValue == otherValue) return NSOrderedSame;
return (myValue < otherValue ? NSOrderedAscending : NSOrderedDescending);
}
#end
a NSDictionary is not ordened, so it doens't matter in what order you construct a NSDIctionary.
a NSArray is ordened. If you want to have the NSDictionary ordened in memory, you should somehow make a NSArray of key value pairs. You can also return two NSArrays with corresponding indeces.
If you only want to iterate over the elements way, you can iterate over a sorted array of keys (this is what koregan suggests).

Find indices of duplicates in a NSArray

i have an array like
[chapter,indent,left,indent,nonindent,chapter,chapter,indent,indent,left];
i need to find indexes of duplicates and also non duplicate elements .
how to do this...........give some sample code or logic......
thanks in advance
iam using objective c.....
NSArray *myWords = [string componentsSeparatedByString:#"class=\""];
int count_var=[myWords count];
tmp1=#"";
for(int i=1;i<count_var;i++)
{
str=[NSString stringWithFormat:#"\n%#",[myWords objectAtIndex:i]];
class=[str componentsSeparatedByString:#"\""];
NSString *tmp=[NSString stringWithFormat:#"%#",[class objectAtIndex:0]];
tmp1=[[NSString stringWithFormat:#"%#",tmp1] stringByAppendingString:[NSString stringWithFormat:#"%#",tmp]];
}
t1.editable=NO;
t1.text=tmp1;
NSArray *tempo=[[NSArray alloc]init];
tempo=[tmp1 componentsSeparatedByString:#"\n"];
tempCount=[tempo count];
this is my sample code...in this the array tempo contains all objects from that array i want to get index of duplicate stringsā‰„.
You could build a dictionary mapping the objects to index sets. For every index set, a -count of 1 means no duplicates, > 1 means there are duplicates.
NSArray *arr = [NSArray arrayWithObjects:...];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (NSUInteger i=0; i<[arr count]; ++i) {
id obj = [arr objectAtIndex:i];
NSMutableIndexSet *ids = [dict objectForKey:obj];
if (!ids) {
ids = [NSMutableIndexSet indexSet];
[dict setObject:ids forKey:obj];
}
[ids addIndex:i];
}
NSLog(#"%#", dict);