How to compare elements in int array to a integer? - iphone

I want to compare an array containing int values to a number
example [1,2,30,1,40,200,10,500] < 500 meaning if array contains elements less than 500.
How can i do dis?
Thank alot in advance
I did this bt it say invalid opernd:
if ([placeName count])
{
for (int i =0; i < [placeName count]; i++)
{
NSArray *sortedArray=[placeName sortedArrayUsingFunction:intSort context:NULL];
self.placeName = [NSMutableArray arrayWithArray:sortedArray];
NSMutableArray *tempArray = [sortedArray objectAtIndex:i];
NSDecimalNumber *Distance = [tempArray objectForKey:#"distance"];
NSMutableArray *intDistanse=[Distance intValue];
DLog(#"Distance%d", intDistanse);
NSMutableArray *intDistanse=[Distance intValue];
DLog(#"Distance%d", intDistanse);
for(int j = 0; j < [intDistanse count]; j++)
{
if ( intDistanse[j] < 500 ) //here its says error
{
DLog(#"success");
}
}
}
}

What kind of an array? NSArray or language array?
Easiest way is a loop. Without knowing the type of the array, this is pseudo code.
for(int i = 0; i < arrayCount; i++)
if ( array[i] < 500 )
.... got an element less than 500 ....
The code doesn't really make sense:
that code should be generating a ton of compiler warnings; every warning indicates a bug that should be fixed. Also, try "Build and Analyze".
you are sorting an array every time through the loop; waste of resources and doesn't make sense
everything being typed as NSMutableArray* doesn't make sense; do you really have an array of arrays of arrays?
... calling objectForKey: on anything but an NSDictionary doesn't work
intValue returns an (int), not an NSMutableArray*
if intDistance is an (int), then it should just be ( intDistance < 500 )
Overall, I would suggest you step back and review the Objective-C language guide and a bunch of working examples.

Typically, you loop over each element in the array, checking if each element is less than 500.
For example:
int i;
for (i=0; i < THE_SIZE_OF_THE_ARRAY; ++i)
{
if (array[i] < 500)
{
/* Do something */
}
}

If you want to see whether there is at least one item that matches your condition:
bool found = false;
for(int i = 0; i < sizeof(example)/sizeof(example[0]); ++i)
{
if(example[i] < 500)
{
found = true;
break;
}
}
And if you want to check whether all items match your condition:
bool found = true;
for(int i = 0; i < sizeof(example)/sizeof(example[0]); ++i)
{
if(example[i] >= 500)
{
found = false;
break;
}
}

Did find a solution to it type casting:
NSMutableArray *tempArray = [sortedArray objectAtIndex:i];
//DLog(#"sortedArray%#", sortedArray);8=
NSNumber *DistanceNum = [tempArray objectForKey:#"distance"];
NSLog(#"distance%#:::",DistanceNum);
NSInteger intDistance = (int)[DistanceNum floatValue];
if(intDistance<500)
{
NSLog(#"h:)");
NSString *notifications =#"Yes";
[[AppHelper mDataManager] setObject:notifications forKey:#"notifications"];
NSLog(#"notifications:%#",notifications);
RemindMeViewController *object = [[RemindMeViewController alloc] initWithNibName:#"RemindMeViewController" bundle:nil];
// RemindMeViewController *object=[[RemindMeViewController alloc]initWithNibName];
NSLog(#"notifications set");
[object scheduleNotification];
}

You can do this very easily by just implementing the observer to compare. Following is just an example to implement the custom observer to compare
#implementation NSArray (KVO)
- (void)addObserver:(NSObject *)observer toObjectsAtIndexes:(NSIndexSet *)indexes forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context
{
NSUInteger idx=[indexes firstIndex];
while(idx!=NSNotFound)
{
[[self objectAtIndex:idx] addObserver:observer
forKeyPath:keyPath
options:options
context:context];
idx=[indexes indexGreaterThanIndex:idx];
}
}
- (void)removeObserver:(NSObject *)observer fromObjectsAtIndexes:(NSIndexSet *)indexes forKeyPath:(NSString *)keyPath
{
NSUInteger idx=[indexes firstIndex];
while(idx!=NSNotFound)
{
[[self objectAtIndex:idx] removeObserver:observer
forKeyPath:keyPath];
idx=[indexes indexGreaterThanIndex:idx];
}
}
-(void)addObserver:(id)observer forKeyPath:(NSString*)keyPath options:(NSKeyValueObservingOptions)options context:(void*)context;
{
if([isa instanceMethodForSelector:_cmd]==[NSArray instanceMethodForSelector:_cmd])
NSRaiseException(NSInvalidArgumentException,self,_cmd,#"not supported for key path %# (observer was %#)", keyPath, observer);
else
[super addObserver:observer
forKeyPath:keyPath
options:options
context:context];
}
-(void)removeObserver:(id)observer forKeyPath:(NSString*)keyPath;
{
if([isa instanceMethodForSelector:_cmd]==[NSArray instanceMethodForSelector:_cmd])
NSRaiseException(NSInvalidArgumentException,self,_cmd,#"not supported for key path %# (observer was %#)", keyPath, observer);
else
[super removeObserver:observer
forKeyPath:keyPath];
}
#end

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.

How to store objects of a mutable Array into another mutable array in form of arrays.?

I have an NSMutable array which contains some objects and I want to store these objects into a different Mutable array in the form of different arrays.
For ex: I have an array named sessionArrayType4 which has these objects.
"New Attendee Reception",
"Attendee Reception",
"Banquett",
"Tour and BBQ"
And I want to store in another Mutable array named globalSessionArray and I'm expecting result something like below.
(("New Attendee Reception"), ("Attendee Reception"), (Banquett), (Tour and BBQ))
Here is my code:
if(self.pickerSelectedRow == [self.typePickerArray objectAtIndex:3])
{
for (int i =0; i< [self.sessionArrayType4 count]; i++)
{
if(self.displayTime == [[self.sessionArrayType4 objectAtIndex:i]valueForKey:#"start_time"])
{
[self.sessionRowArray addObject:[[self.sessionArrayType4 objectAtIndex:i]valueForKey:#"session_name"]];
self.rowCount = self.rowCount + 1;
}
else
{
[self.sessionRowArray removeAllObjects];
self.displayTime = [[self.sessionArrayType4 objectAtIndex:i] valueForKey:#"start_time"];
[self.sessionRowArray addObject:[[self.sessionArrayType4 objectAtIndex:i]valueForKey:#"session_name"]];
[self.globalSessionArray addObject:self.sessionRowArray];
}
}
}
But I am getting output something like this:
((Tour and BBQ), (Tour and BBQ), (Tour and BBQ), (Tour and BBQ))
You're going to have to alloc/init your values into an object for each iteration of the for loop or else it will continually stick in memory and overwrite itself.
if(self.pickerSelectedRow == [self.typePickerArray objectAtIndex:3])
{
NSArray *
for (int i =0; i< [self.sessionArrayType4 count]; i++)
{
NSObject *myNewObject = [[NSObject alloc] init];
if(self.displayTime == [[self.sessionArrayType4 objectAtIndex:i]valueForKey:#"start_time"])
{
myNewObject = [[self.sessionArrayType4 objectAtIndex:i]valueForKey:#"session_name"];
[self.sessionRowArray addObject: myNewObject];
self.rowCount = self.rowCount + 1;
}
else
{
[self.sessionRowArray removeAllObjects];
//NSLog(#"%#",self.sessionRowArray);
self.displayTime = [[self.sessionArrayType4 objectAtIndex:i] valueForKey:#"start_time"];
myNewObject = [[self.sessionArrayType4 objectAtIndex:i]valueForKey:#"session_name"]];
[self.sessionRowArray addObject:myNewObject];
// NSLog(#"%#",self.sessionRowArray);
[self.globalSessionArray addObject:self.sessionRowArray];
// NSLog(#"%#",self.globalSessionArray);
}
}
}
You need to allocate an temp array in for loop to get a final array of arrays.
The code is very confusing but you can modify like below to get correct result:
if(self.pickerSelectedRow == [self.typePickerArray objectAtIndex:3])
{
for (int i =0; i< [self.sessionArrayType4 count]; i++)
{
if(self.displayTime == [[self.sessionArrayType4 objectAtIndex:i]valueForKey:#"start_time"])
{
[self.sessionRowArray addObject:[[self.sessionArrayType4 objectAtIndex:i]valueForKey:#"session_name"]];
self.rowCount = self.rowCount + 1;
}
else
{
[self.sessionRowArray removeAllObjects];
NSMutableArray* tempArray = [[NSMutableArray alloc] init];
//NSLog(#"%#",self.sessionRowArray);
self.displayTime = [[self.sessionArrayType4 objectAtIndex:i] valueForKey:#"start_time"];
[tempArray addObject:[[self.sessionArrayType4 objectAtIndex:i]valueForKey:#"session_name"]];
// NSLog(#"%#",self.sessionRowArray);
[self.globalSessionArray addObject:tempArray];
// NSLog(#"%#",self.globalSessionArray);
}
1)
if(self.pickerSelectedRow == [self.typePickerArray objectAtIndex:3])
This expression and similar ones look like incorrect, because the left value look likes int or NSInteger and right value is NSObject. If they are both NSObjects then use isEqual instead.
2)
sessionArrayType4
it is correct, but no serious programmer uses such names for variables.
3)It is hard to understand what do you want because of incomplete code and a lot of NSLog calls. You have also added JSON code which is particularly incompatible with a previous part of code.
So edit your code first

How to position the untitled section in a UITableView

At present if the sortdescriptor is having nil or empty values is being placed in an untitled section which is being placed at the top of the table. I want it to be at the end of the table. Any suggestions?
yes, it is so easy, jst perform a segmentation in which start by the charecter A and check upto z, (or whatever your requiremtn) if it matches nothing, then add it to last array that you are going to show in untititled objects. i have this for contacts. see if it is understandable by u
int numContacts=[cList count];
//NSMutableArray *nonAlphaArray=[[NSMutableArray alloc] init];
NSMutableArray *arrayCollection[27];
for (int i=0; i<27; i++) {
arrayCollection[i]=[NSMutableArray array];
}
for (int i=0; i<numContacts; i++)
{
Contact *contact= [cList objectAtIndex:i];
unichar alphaSmall='a';
unichar alphaBig='A';
unichar first=0x0000;
if([contact.mContactName length]>0)
first= [contact.mContactName characterAtIndex:0];
for (int j=0; j<26; )
{
if (first==alphaSmall || first==alphaBig)
{
[arrayCollection[j] addObject:contact];
break;
}
alphaSmall++;
alphaBig++;
j++;
if (j==26) {
[arrayCollection[26] addObject:contact];
}
}
}
for (int i=0; i<27; i++)
{
[alphaDictionary setObject:arrayCollection[i] forKey:[NSString stringWithFormat:#"%d",i]];
}

How to get index in an NSArray?

NSMutableArray*array = [[NSMutableArray alloc]init];
NSArray*Somearray = [NSArray arrayWithObjects:1st Object,2ndObject,3rd Object,4th object,5th Object,nil];
In the above array 1st Object,2ndObject,3rd Object,4th object,5th Object having val,content,conclusion in each index.
for(int i=0;i<[Somearray count];i++)
{
______________
Here the code is there to give each index ,that is having val,content,conclusion ..
After that val,content,conclusion in each index will be add to Dict..
____________
NSDictionary *Dict = [NSDictionary dictionaryWithObjectsAndKeys:val,#"val",content,#"content",conclusion,#"conclusion",nil];
//Each time adding dictionary into array;
[array addObject:Dict];
}
The above Dictionary is in for loop and the keyvalue pairs will be add 5 times(Somearray Count).Now array is having in
array = [{val="1.1 this is first one",content="This is the content of 0th index",conclusion="this is the conclusion of 0th index"},{val="1.2 this is first one",content="This is the content of 1st index",conclusion="this is the conclusion of 1st index"},____,____,______,{val="1.5 this is first one",content="This is the content of 4th index",conclusion="this is the conclusion of 4th index"},nil];
Now i am having NSString*string = #"1.5";
Now i need the index where val is having 1.5 in it.How to send the str in to array to find the the index.
Can anyone share the code please.
Thanks in advance.
Use method indexOfObject
int inx= [array indexOfObject:#"1.5"];
For Find index particular key value.
int inx;
for (int i=0; i<[array count]; i++) {
if ([[[array objectAtIndex:i] allKeys] containsObject:#"val"]) {
inx=i;
break;
}
}
The method you are looking for is -[NSArray indexOfObjectPassingTest:]. You would use it like this:
NSUInteger i = [array indexOfObjectPassingTest:^(id obj, NSUInteger idx, BOOL *stop) {
return [[id objectForKey:#"val"] rangeOfString:#"1.5"].location != NSNotFound;
}];
If you just want to check that val starts with "1.5" you would use hasPrefix: instead.
Try this -
NSArray *valArray = [array valueForKey:#"val"];
int index = [valArray indexOfObject:#"1.5"];
Appended answer given by Mandeep, to show you the magic of key value coding ;)
NSUInteger idx = UINT_MAX;
NSCharacterSet* spaceSet = [NSCharacterSet whitespaceCharacterSet];
for(int i=0,i_l=[Yourarray count];i<i_l;i++) {
NSString* s_prime = [[Yourarray objectAtIndex:i] valueForKey:#"val"];
if ([s_prime length] < 4) {
continue;
}
NSString *subString = [[s_prime substringToIndex:4] stringByTrimmingCharactersInSet:spaceSet];
// NSLog(#"index %#",s);
if ([subString isEqualToString:secretNumber]){
idx = i;
break;
}
}
if (idx != UINT_MAX) {
// NSLog(#"Found at index: %d",idx);
} else {
// NSLog(#"Not found");
}

How to compare array element?

Suppose I have an array having elements "am","john","rosa","freedom". I want to compare these elements and result would be the word and the size of the longest word. I am using objective C.
There isn't a "built-in" way of doing this, however you can use NSArray's sortedArrayUsingSelector: and create a category on NSString to provide a lengthCompare: method.
// NSString+LengthCompare.h
#import NSString.h
#interface NSString (LengthComparison)
- (NSComparisonResult)lengthCompare:(NSString *)aString;
#end
// NSString+LengthCompare.m
#import NSString+LengthCompare.h
#implememtation NSString (LengthComparison)
- (NSComparisonResult)lengthCompare:(NSString *)aString
{
if ([self length] < [aString length]) {
return NSOrderedAscending;
} else if ([self length] > [aString length]) {
return NSOrderedDescending;
} else {
return NSOrderedSame;
}
}
#end
Now you can sort an of strings in ascending order using lengthCompare:
NSArray *array = [NSArray arrayWithObjects: #"am", #"john", #"rosa", #"freedom", nil];
NSArray *arraySortedByStringLength = [array sortedArrayUsingSelector:#selector(lengthCompare:)];
NString *shortestWord = [[arraySortedByStringLength objectAtIndex:0] retain];
NSLog(#"shortest word, %# has length %d", shortestWord, [shortestWord length];
[shortestWord release];
NString *longestWord = [[arraySortedByStringLength lastObject] retain];
NSLog(#"Longest word, %# has length %d", longestWord, [longestWord length];
[longestWord release];
Sounds like a classical logic exercise or is it something I miss in your question ?
int longestWordIndex = 0;
NSUInteger longestWordSize = 0;
for (int i=0 ; i<[nameArray count] ; i++) {
NSString* element = (NSString*)[nameArray objectAtindex:i];
if([element lenght] > longestWordSize) {
longestWordSize = [element lenght];
longestWordIndex = i;
}
}
NSLog("Longest word is %# with size of :%d", [nameArray objectAtIndex:longestWordIndex], longestWordSize);
I'll add one more approach to the two above -- use a block to do the body of your iteration.
__block NSUInteger longestWordSize = -1; // Make sure at least one object will be longer.
__block NSUInteger longestWordIndex;
[nameArray enumerateObjectsUsingBlock:^(id currentWord, NSUInteger index, BOOL *stop) {
if ([currentWord length] > longestWordSize) {
longestWordSize = [currentWord length];
longestWordIndex = index;
}
}];
NSLog("Longest word is %# with size of :%d", [nameArray objectAtIndex:longestWordIndex], longestWordSize);
Edit: The max and index have to be of storage type __block so they can be changed from inside the block.