Create a NSPredicate to find elements whose length is > N - iphone

I have an array of strings ( more that 5k elements), each of variable length. I can use NSPredicate to find specific strings within the array( took a bit to figure that out). Now I need to find elements whose length is > than N.
I have looked through the documentation and Length does not seem to be one of the functions available in the Predicate Programming Guide.
Thanks in advance.
Imagmast

NSArray * words= [allLinedStrings filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"length > %d",N]];
N is your integer as you mentioned in your question.

I'm not familiar with NSPredicate, so I can't give you a solution using it, but couldn't you just use some plain NSString methods:
//This is the length of the string you want to check
int threshold = 5;
//Iterates through all elements in the array
for(int index = 0; index < [stringArray count]; index++) {
//Checks if the length of the string stored at the current index is greater than N
if([[stringArray objectAtIndex:index] length] > threshold) {
//String length is greater than N
}
}
Optionally, you could add in a check to see if the array only has strings (sacrifices performance for safety) by replacing this line:
if([[stringArray objectAtIndex:index] length] > threshold)
With this:
if([[stringArray objectAtIndex:index] length] > threshold && [[stringArray objectAtIndex:index] isKindOfClass[NSString class]])
What this does is it makes sure that the object at the current index is an NSString. If it's not, you'd receive a runtime error.

Related

Finding multiple numerations of a character in UITextView

I am a UITextView where I am trying to find the # character. The text view might have multiple #s, so I was wondering, how can I find the nth # character?
Currently, I have: NSRange range = [textViewText rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:#"#"]];. This only finds the first # instance. How can I find subsequent ones?
You could try doing something like splitting up the text based on #"#" and then you know where the components are split, thats where the # should appear. This way you can easily find the nth #
If I understand you question correctly, a regular expression would solve you problem.
RegEx has a bit of a learning curve but it comes in handy very often.
http://www.regular-expressions.info/
is a very good starting point for regular expressions in general
http://remarkablepixels.com/blog/2011/1/13/regular-expressions-on-ios-nsregularexpression.html
A tutorial about regular expression in iOS
http://reggyapp.com/
Reggy is an osx app in which you can test your RegEx on actual text.
What do you want to do once you've located the nth #?
Here's some sample code that sketches a solution. Not compiled or checked for bugs!
int targetItem = 3; // we find the 3rd item
NSString *workingStr = #"your#string#containing#stuff";
int foundAtLocation = -1;
for (int idx = 0; idx < targetItem; idx++) {
NSRange range = [workingStr rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:#"#"]];
if (range.location < 0) {
// not found, give up
foundAtLocation = -1;
break;
}
workingStr = [workingStr substringFromIndex:range.location];
foundAtLocation += range.location;
}
if (foundAtLocation >= 0) {
NSLog(#" I found the %d occurence of # at character index %d", targetItem, foundAtLocation);
}
else {
NSLog(#" Not found");
}

Confusing arrays

Kinda new to iOS, Im also studying Android. kinda confuse on arrays.
How to convert this into iOS:
result as being the index
nextresult[x] array of indexes
for(x = 0; x < array.size; x++)
{
if(result < nextresult[x])
nextresult[x] -= 1;
}
It will iccheck all of the content of the arrays if it needs to be adjusted or not,
Might be following will give you some idea -
As you mentioned, i have considered following - result' is value andnextresult` is array.
for(x = 0; x < [array count]; x++)
{
if(result < [nextresult objectAtIndex:x]) {
[nextresult objectAtIndex:x] -= 1;
}
}
EDIT -
if you want to add integer in arrays -
[yourArray addObject:[NSNumber numberWithInt:1]]; // Objective C array store objects. so we need to convert primitive data type into object.
Read Apple's excellent developer documentation.
You can find the docs about the NSArray class here, or in your Xcode organizer.
I have downvoted your question, because it could very easily have been solved by just looking at the docs.

IndexOfObject return 2147483647

I have an array with 10 items. When I call "IndexOfObject" for the elements number 9 and the element number 10 Xcode return an exception: "NSRangeException"
reason: '_[_NSCFArray objectAtIndex:] index:2147483647 beyond
bounds(10)'.
From a previous NSLog, I saw that the two elements exist in the array but indexOfObject not find them. Why?
My code is:
NSDictionary * headConfig =[avatarDictionaryToSave objectForKey:#"head_dictionary"];
NSString * headImage =[headConfig objectForKey:#"layer_key"];
NSString * pathFace =[[NSBundle mainBundle]pathForResource:#"Face" ofType:#"plist"];
NSLog(#"%#", headImage);
NSArray *arrayFace =[NSArray arrayWithContentsOfFile:pathFace];
NSLog(#"the elements are: %#", arrayFace);//here headImage is present
int index =[arrayFace indexOfObject:headImage];
NSLog(#"the index is %d", index);
indexOfObject: returns NSNotFound when the object is not present in the array. NSNotFound is defined as NSIntegerMax (== 2147483647 on iOS 32 bit).
So it seems that the object you are looking for is just not there.
Please change the coding of adding the array values as I mentioned below.
// [arr_values addObject:[dictionary valueForKey:#"Name"]];
[arr_values addObject:[NSString stringWithFormat:#"%#",[dictionary valueForKey:#"Name"]]];
When target array elements are not in string format then while we using the
indexOfObject then that value can't able to find in the target array. So please try to
change the value of object as mentioned above while adding into array.
By default, an integer is assumed to be signed.
In other words the compiler assumes that an integer variable will be called upon to store either a negative or positive number. This limits the extent that the range can reach in either direction.
For example, a 32-bit int has a range of 4,294,967,295. In practice, because the value could be positive or negative the range is actually −2,147,483,648 to +2,147,483,647.
If we know that a variable will never be called upon to store a negative value, we can declare it as unsigned, thereby extending the (positive) range to 0 to +4,294,967,295.
An unsigned int is specified as follows:
unsigned int myint;

Trying to sort multidimensional mutable array with one (integer) object

I have an multidimensional NSMutableArray and I want to sort it on one of the objects. The array is created so:
[NSMutableArrayName addObjectsFromArray:[NSMutableArray arrayWithObjects:[NSMutableArray arrayWithObjects:name,[NSNumber numberWithInteger:x],nil],nil]];
I can't find a way to sort the entire array using the value of the second object (the integer x).
Help appreciated as always.
This sounds like a good case for sortUsingComparator:. You use it something like this:
[NSMutableArrayName sortUsingComparator:^NSComparisonResult(id o1, id o2){
NSInteger a = [[o1 objectAtIndex:1] integerValue]; // Or however to extract the int from your array element
NSInteger b = [[o2 objectAtIndex:1] integerValue];
if (a < b) return NSOrderedAscending;
if (a > b) return NSOrderedDescending;
return NSOrderedSame;
}];
If you're targeting pre-iOS 4.0, you can accomplish much the same thing using sortUsingFunction:context: and putting the block content into a C-style function.

Access NSMutableArray to an index with no value

if i try to access a nsmutableArray with objectAtIndex:x and if i have no object at this index, my app always crash.
So my question is: how can i check, if there is something at this index, without crashing the app?
I hope your understand my question.
Thanks, Alex
Check if your index is in array's bounds range:
if (index >=0 && index < [myArray count])
...
NSArray has a method called "count".
Call count on your mutable array and it will tell you the number of elements in the array.
You have two options: Use the count method to ensure you're within the bounds of the array, or catch the exception when you try to use objectAtIndex: Checking the range with count will be much lower overhead than catching the exception.
In case you didn't know - there are no "holes" allowed in an NSArray - the objects from index 0 to the end of the array ([array count]-1) will all be accessible.
If you are within the array's bounds, you will always have an object at a specific index between 0 and [array count], as the array cannot have gaps of nil values in it.
Try this
for(i=0; i< [myMutableArrayObject count]; i++) {
NSLog(#"%#",[[myMutableArrayObject objectAtIndex: i] myMethodDefined]);
}
Here, we are using a method predefined called count which returns the number of objects in the MutableArray Object
and then another method objectAtIndex which iterates the objects at the interval from 0 to (count – 1).
Regards,
Sumit