How to check if NSMutableArray object contains NaN [duplicate] - iphone

This question already has answers here:
Determine if NSNumber is NaN
(9 answers)
Closed 9 years ago.
I have an NSMutableArray with 1 float value and 4 nan values. I want to execute some operations if the array object is nan. How can I write an if condition?

try isnan function
Iterate your array and put check
isnan([[Array objectAtIndex:i] floatValue])
(dont forget to add math.h library)

NSNumber *num = //your number;
float value = [num floatValue];
if (isnan(value))
{
NSLog(#"is nan");
}

Do something like this:
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:[NSNumber numberWithFloat:1.0]];
[array addObject:[NSNull null]];
[array addObject:[NSNull null]];
[array addObject:[NSDecimalNumber notANumber]];
BOOL foundNull = NO;
for (id value in array) {
if (!value || value == [NSNull null]) {
foundNull = YES;
} else if ([value isKindOfClass:[NSDecimalNumber class]]) {
if ([value isEqualToNumber:[NSDecimalNumber notANumber]]) {
foundNull = YES;
}
}
}
NSLog(#"Found null/NaN: %i", foundNull);

You can also use
[NSDecimalNumber notANumber] method to compare and check if this a valid number or not.

Related

Sort NSArray for a specific order

I have an NSArray of custom objects.
Each object contains one integer value for ex. 1,2,3,4
Now I want to sort Array like below
9 7 5 3 1 2 4 6 8
Could some one help me?
Here is your answer.
Hope your first array is in sorted order (ascending) if not then you need to sort it first.
NSMutableArray *myArray = [NSMutableArray array];
//Populate your array with custom objects. I had created my own which contain an integer type property.
[myArray addObject:[[myObject alloc] initWithId:11 objectName:#"K"]];
[myArray addObject:[[myObject alloc] initWithId:3 objectName:#"C"]];
[myArray addObject:[[myObject alloc] initWithId:4 objectName:#"D"]];
....
...
.... and so on
then sort it in Ascending order. You can do it Descending also but then you need to change the below logic little bit. I showing with Ascending order.
NSArray *tempArray = [myArray sortedArrayUsingComparator:^NSComparisonResult(myObject *obj1, myObject *obj2) {
if([obj1 objectId] > [obj2 objectId]) return NSOrderedDescending;
else if([obj1 objectId] < [obj2 objectId]) return NSOrderedAscending;
else return NSOrderedSame;
}];
Now sort them as per your requirement
NSMutableArray *finalArray = [NSMutableArray arrayWithArray:tempArray];
NSInteger totalObjects = [tempArray count];
NSInteger centerObjectIndex = totalObjects>>1;
__block NSInteger rightPosition = centerObjectIndex + 1;
__block NSInteger leftPosition = centerObjectIndex - 1;
__block BOOL toggle = NO;
[tempArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if(idx == 0) [finalArray replaceObjectAtIndex:centerObjectIndex withObject:obj];
else
{
if(toggle)
{
if(leftPosition >= 0)
{
[finalArray replaceObjectAtIndex:leftPosition withObject:obj];
leftPosition -= 1;
}
}
else
{
if(rightPosition < totalObjects)
{
[finalArray replaceObjectAtIndex:rightPosition withObject:obj];
rightPosition += 1;
}
}
toggle = !toggle;
}
}];
Here is the final step if your array contains an even numbers of objects
if(!(totalObjects % 2))
{
[finalArray removeObjectAtIndex:0];
[finalArray addObject:[tempArray objectAtIndex:totalObjects-1]];
}
Now you are at end. Your array named finalArray get sorted as per your requirement.

compare Integer values using array

I have some integer values inside NSMutableArray. I have added a UITextField and a UIButton. If a number is entered inside textfield and clicking on the button does a comparison. If number entered matches, I need to show NSLog. But it's not working.
code:
arr = [[NSMutableArray alloc]init];
[arr addObject:[NSNumber numberWithInteger:1]];
Button click:
-(void)click:(id)sender{
if (text.text == [arr objectAtIndex:0]){
NSLog(#"values matched");
}
}
Try this
-(void)click:(id)sender{
NSString *str = [NSString alloc]initWithFormat:#"%d",[arr objectAtIndex:0]];
if([text.text isEqualToString: str]){
NSLog(#"values matched");
}
}
I am assuming the array contains NSNumber objects; and if so convert the textfield content to an NSNumber object and use [NSArray indexOfObject] to find it in the array:
- (void)click:(id)sender{
NSNumber *num = [NSNumber numberWithInt:[text.text intValue]];
NSUInteger index = [arr indexOfObject:num];
if (index != NSNotFound) {
NSLog(#"values matched");
}
}

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]

how to remove NULL values from NSMutableArray? ios

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];
}
}
}

how do I create fresh NSMutableArray?

I have an NSMutableArray which only lasts during the session.
Currently I create it like this
NSMutableArray *temp = [[NSMutableArray alloc] initWithCapacity:10];
[self setScoreArray:temp];
[temp release];
Problem is when I go to check each index I'm getting an array outofbounds error
NSNumber *previousScore = [[self scoreArray] objectAtIndex:[self quizNum]];
if ( previousScore != nil )
{
[self clearQuizBtns];
NSInteger previousScoreValue = [previousScore integerValue];
[self selectButtonAtTag:previousScoreValue];
}else {
[self clearQuizBtns];
}
I've read in other posts that initWithCapacity doesn't actually create the array. So what can I populate the array with initially?
Thanks in advance.
Two ways:
first: to initiate array with default values of NSNull class
NSMutableArray *temp = [[NSMutableArray alloc] initWithCapacity:10];
for (int i = 0 ; i < 10 ; i++)
{
[temp insertObject:[NSNull null] atIndex:i];
}
[self setScoreArray:temp];
[temp release];
and then to check: if object is kind of NSNull class means it was a never set before
id previousScore = [[self scoreArray] objectAtIndex:[self quizNum]];
if (![previousScore isKindOfClass:[NSNull class]])
{
[self clearQuizBtns];
NSInteger previousScoreValue = [(NSNumber *)previousScore integerValue];
[self selectButtonAtTag:previousScoreValue];
}else {
[self clearQuizBtns];
}
second: store scores in NSMutableDictionary and use NSNumber's as keys
// scoreDictionary property of NSMutableDictionary class must be declared in self
NSNumber *previousScore = [self.scoreDictionary objectForKey:[NSNumber numberWithInt:[self quizNum]]];
if (previousScore != nil)
{
[self clearQuizBtns];
NSInteger previousScoreValue = [previousScore integerValue];
[self selectButtonAtTag:previousScoreValue];
}else {
[self clearQuizBtns];
}
NSArray does not support "holes". The capacity is just a hint to the initializer.
You could either fill the array with placeholder objects or, more typically, change your algorithm to either fully prepopulate the array or to lazy load it linearly.
Your problem seems to be that you're never actually setting any score in the score array.. are you? NSArrays have an actual count of items in them, and accessing an index beyond that count will blow up, as you've seen. If there will only ever be a fixed (small) number of scores, like 10, then you could set them all initially to something default like:
for (int i = 0; i < 10; i++) {
[temp addObject:[NSNumber numberWithInt:0]];
}
P.S. -initWithCapacity does "create the array", it just doesn't create any objects in the array. The capacity is a hint only.
Using the arrayWithObject: or arrayWithObjects: methods can provide an array with pre-populated values.
One cool thing about NSMutableArrays is that you can just do an "init" and the array will handle adding and removing objects on the fly. Remember that you generally addObject: or removeObjectAtIndex: when dealing with mutable arrays.