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");
}
}
Related
I found a workaround myself, but still trying to understand the problem.
I created a Autocomplete text field with the use of uitableview which is hidden until textfield is edited. The UI part works fine. It's the searching for the results part that's the problem. I declared a local NSMutableDictionary to store my results because I wanted the results to be sorted by the key's values.
if I call keysSortedByValueUsingSelector on the dictionary directly, it crashes. However if I get the keys by [dict allKeys] first, then call sortedArrayUsingSelector, it works fine:
// This commented out line will crash
// NSArray *sortedKeysArray = [dict keysSortedByValueUsingSelector:#selector(compare:)];
// The next two lines runs fine.
NSArray *keyArray = [dict allKeys];
NSArray *sortedKeysArray = [keyArray sortedArrayUsingSelector:#selector(compare:)];
Here is the complete source code for the search method:
- (void)searchAutocompleteEntriesWithSubstring:(NSString *)substring
{
// Put anything that starts with this substring into the autocompleteUrls array
// The items in this array is what will show up in the table view
[autocomplete_symbol_array removeAllObjects];
rRSIAppDelegate *appDelegate = (rRSIAppDelegate *)([[UIApplication sharedApplication] delegate]);
NSString *input_str = [substring uppercaseString];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
int i = 0;
for(SymbolInfo *symbol_info in appDelegate.m_symbol_info_array)
{
i++;
NSString *info_str = [[[symbol_info.m_symbol uppercaseString] stringByAppendingString:#"|"] stringByAppendingString:[symbol_info.m_company_name uppercaseString]];
NSUInteger pos = [info_str rangeOfString:input_str].location;
if (pos != NSNotFound)
{
int tmp = pos * 10000 + i;
NSNumber *map_key = [[NSNumber alloc] initWithInt:tmp];
[dict setObject:symbol_info forKey:map_key];
}
}
// This commented out line will crash
// NSArray *sortedKeysArray = [dict keysSortedByValueUsingSelector:#selector(compare:)];
// The next two lines runs fine.
NSArray *keyArray = [dict allKeys];
NSArray *sortedKeysArray = [keyArray sortedArrayUsingSelector:#selector(compare:)];
for (NSNumber *key in sortedKeysArray)
{
SymbolInfo *symbol_info = [dict objectForKey:key];
[autocomplete_symbol_array addObject:symbol_info];
}
// NSLog(#"everything added: %d", [autocomplete_symbol_array count]);
[autocompleteTableView reloadData];
}
The NSMutableDictionary's method is:
- (void)setObject:(id)anObject forKey:(id < NSCopying >)aKey;
This means that the key should implement the NSCopying protocol.
I have an array which contains some strings. For each character of a string an integer value is assigned. For example a=2,b=5,c=6 ,o=1,k=3 etc
The final value in the a string is the sum of the character's value. So that for an example string "BOOK" the string will be stored as "BOOK (7)". Similarly every string will have a final integer value. I would like to sort these array with these final integer values stored in the string which is present in each array index. The array contains more than 200,000 words. So the sorting process should be pretty fast. Is there any method for it?
A brutal quick example could be, if your strings structure is always the same, like "Book (7)" you can operate on the string by finding the number between the "()" and then you can use a dictionary to store temporally the objects:
NSMutableArray *arr=[NSMutableArray arrayWithObjects:#"Book (99)",#"Pencil (66)",#"Trash (04)", nil];
NSLog(#"%#",arr);
NSMutableDictionary *dict=[NSMutableDictionary dictionary];
//Find the numbers and store each element in the dictionary
for (int i =0;i<arr.count;i++) {
NSString *s=[arr objectAtIndex:i];
int start=[s rangeOfString:#"("].location;
NSString *sub1=[s substringFromIndex:start];
NSString *temp1=[sub1 stringByReplacingOccurrencesOfString:#"(" withString:#""];
NSString *newIndex=[temp1 stringByReplacingOccurrencesOfString:#")" withString:#""];
//NSLog(#"%d",[newIndex intValue]);
[dict setValue:s forKey:newIndex];
}
//Sorting the keys and create the new array
NSArray *sortedValues = [[dict allKeys] sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
NSMutableArray *newArray=[[NSMutableArray alloc]init];
for(NSString *valor in sortedValues){
[newArray addObject:[dict valueForKey:valor]];
}
NSLog(#"%#",newArray);
This prints:
(
"Book (99)",
"Pencil (66)",
"Trash (04)"
)
(
"Trash (04)",
"Pencil (66)",
"Book (99)"
)
as i understand, you want to sort an array which contains string formated in the following
a=3
and you want to sort according to the number while ignoring the character.
in this case the following code will work with you
-(NSArray *)Sort:(NSArray*)myArray
{
return [myArray sortedArrayUsingComparator:(NSComparator)^(id obj1, id obj2)
{
NSString *first = [[obj1 componentsSeparatedByString:#"="] objectAtIndex:1];
NSString *second = [[obj2 componentsSeparatedByString:#"="] objectAtIndex:1];
return [first caseInsensitiveCompare:second];
}];
}
How to use it:
NSArray *arr= [[NSArray alloc] initWithObjects:#"a=3",#"b=1",#"c=4",#"f=2", nil];
NSArray *sorted = [self Sort:arr];
for (NSString* str in sorted)
{
NSLog(#"%#",str);
}
Output
b=1
f=2
a=3
c=4
Try this methods
+(NSString*)strTotalCount:(NSString*)str
{
NSInteger totalCount = 0;
// initial your character-count directory
NSDictionary* characterDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:2], [NSString stringWithUTF8String:"a"],
[NSNumber numberWithInt:5], [NSString stringWithUTF8String:"b"],
[NSNumber numberWithInt:6], [NSString stringWithUTF8String:"c"],
[NSNumber numberWithInt:1], [NSString stringWithUTF8String:"o"],
[NSNumber numberWithInt:3], [NSString stringWithUTF8String:"k"],
nil];
NSString* tempString = str;
for (NSInteger i =0; i<tempString.length; i++) {
NSString* character = [tempString substringWithRange:NSMakeRange(i, 1)];
character = [character lowercaseString];
NSNumber* count = [characterDictionary objectForKey:character];
totalCount += [count integerValue];
};
return [NSString stringWithFormat:#"%#(%d)",str,totalCount];
}
The test sentence:
NSLog(#"%#", [ViewController strTotalCount:#"BOOK"]);
will output " BOOK(10) "
You may change the ViewController to you own class name;
First - create a custom object to save your values. Don't put the value inside the string.
Sorting is not your base problem. The problem is that you are saving values into a string from where they are difficult to extract.
#interface StringWithValue
#property (nonatomic, copy, readwrite) NSString* text;
#property (nonatomic, assign, readwrite) NSUInteger value;
- (id)initWithText:(NSString*)text;
- (NSComparisonResult)compare:(StringWithValue*)anotherString;
#end
#implementation StringWithValue
#synthesize text = _text;
#synthesize value = _value;
- (id)initWithText:(NSString*)text {
self = [super init];
if (!self) {
return nil;
}
self.text = text;
self.value = [self calculateValueForText:text];
return self;
}
- (NSComparisonResult)compare:(StringWithValue*)anotherString {
if (self.value anotherString.value) {
return NSOrderedDescending;
}
else {
return NSOrderedSame;
}
}
- (NSString*)description {
return [NSString stringWithFormat:#"%# (%u)", self.text, self.value];
}
#end
Sorting the array then would be a simple use of sortUsingSelector:.
Note this will beat all other answers in performance as there is no need to parse the value with every comparison.
I have an array which contains strings like frame_10#3x.png , frame_5#3x.png,frame_19#3x.png etc.
So I want to sort this array according to the number after the underscore i.e. the correct sequence will be frame_5#3x.png,frame_10#3x.png,frame_19#3x.png.
I tried to use the following method but no result:
NSInteger firstNumSort(id str1, id str2, void *context) {
int num1 = [str1 integerValue];
int num2 = [str2 integerValue];
if (num1 < num2)
return NSOrderedAscending;
else if (num1 > num2)
return NSOrderedDescending;
return NSOrderedSame;
}
Please suggest how to do this sorting for array.
NSArray *sry_img = [[NSArray alloc] initWithObjects:#"frame_18#3x.png",#"frame_17#3x.png",#"frame_1222#3x.png",#"frame_10#3x.png",#"frame_3#3x.png",#"frame_4#3x.png",#"frame_4#3x.png",#"frame_1#3x.png",#"frame_4#3x.png",#"frame_4#3x.png",nil];
NSArray *sortedStrings = [sry_img sortedArrayUsingSelector:#selector(localizedStandardCompare:)];
NSLog(#"%#",sortedStrings);
Enjy .......
But
localizedStandardCompare:, added in 10.6, should be used whenever file names or other strings are presented in lists and tables where Finder-like sorting is appropriate. The exact behavior of this method may be tweaked in future releases, and will be different under different localizations, so clients should not depend on the exact sorting order of the strings.
you want to do something like:
NSArray *components1 = [str1 componentsSeparatedByString:#"_"];
NSArray *components2 = [str2 componentsSeparatedByString:#"_"];
NSString *number1String = [components1 objectAtIndex:([components1 count] - 1])];
NSString *number2String = [components2 objectAtIndex:([components2 count] - 1])];
return [number1String compare:number2String];
I am not sure if my solution is the best possible approach but it can solve your problem for the time being :) .
1) First I have written a function to get the numbers before # character in your string and then I implemented simple SELECTION SORT algo to sort the array using this functions.
- (NSString*)getSubStringForString:(NSString*)value {
// First we will cut the frame_ string
NSMutableString *trimmedString = [NSMutableString stringWithString:[value substringWithRange:NSMakeRange(6, [value length]-6)]];
// New String to contain the numbers
NSMutableString *newString = [[NSMutableString alloc] init];
for (int i = 0; i < [trimmedString length] ; i++) {
NSString *singleChar = [trimmedString substringWithRange:NSMakeRange(i, 1)];
if (![singleChar isEqualToString:#"#"]) {
[newString appendString:singleChar];
} else {
break;
}
}
return newString;
}
This is the selection Implementation of the algo for sorting. The main logic is in the for loop. You can copy the code in viewDidLoad method to test.
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:#"frame_10#3x.png",#"frame_5#3x.png",
#"frame_3#3x.png", #"frame_19#3x.png",
nil];
NSLog(#"Values before Sort: %#", array);
int iPos;
int iMin;
for (iPos = 0; iPos < [array count]; iPos++)
{
iMin = iPos;
for (int i = iPos+1; i < [array count]; i++)
{
if ([[self getSubStringForString:[array objectAtIndex:i]] intValue] >
[[self getSubStringForString:[array objectAtIndex:iMin]] intValue]) {
iMin = i;
}
}
if ( iMin != iPos )
{
NSString *tempValue = [array objectAtIndex:iPos];
[array replaceObjectAtIndex:iPos withObject:[array objectAtIndex:iMin]];
[array replaceObjectAtIndex:iMin withObject:tempValue];
}
}
NSLog(#"Sorted Values: %#", array);
I hope that it can atleast keep you going. :)
You can try this-
NSString *str1 = [[[[str1 componentsSeparatedByString:#"frame_"] objectAtIndex:1] componentsSeparatedByString:#"#3x.png"] objectAtIndex:0];
int num1 = [str1 integerValue];
I am having an array like fallowing,
NSArray*array = [NSArray arrayWithObjects:#"1.1 something", #"1.2 something else", #"1.3 out of left field", #"1.4 yet another!", nil];
Now,i am having the string like fallowing,
NSString*str = #"1.3";
Now i will send the str .Then it needs to find that str in array and it need to return the index of object where that text found.Means i need index 2 has to come as output.Can anyone share the code please.Thanks in advance.
Here is an example using blocks, notice the method: hasPrefix:
NSArray *array = [NSArray arrayWithObjects:#"1.1 problem1", #"1.2 problem2", #"1.3 problem3", #"1.4 problem4", nil];
NSString *str = #"1.3";
NSUInteger index = [array indexOfObjectPassingTest:
^(id obj, NSUInteger idx, BOOL *stop) {
return [obj hasPrefix:str];
}];
NSLog(#"index: %lu", index);
NSLog output:
index: 2
First a comment,
NSString *str = 1.3;
does not create an NSString object. You should instead have
NSString *str = #"1.3";
To search the NSArray, you will either have to change the string to the exact string in the array or search the NSString as well. For the former, simply do
float num = 1.3;
NSString *str = [NSString stringWithFormat:#"%.1f problem%d",num,(num*10)%10];
[array indexOfObject:str];
You can get fancier using NSPredicates as well.
Try
NSString *searchString = [str stringByAppendingFormat: #" problem%#", [str substringFromIndex: 2]];
NSUInteger index = [array indexOfObject: searchString];
Or (because you somehow like oneliners):
[array indexOfObject: [[array filteredArrayUsingPredicate: [NSPredicate predicateWithFormat: #"SELF beginswith %#", str]] objectAtIndex: 0]];
The simplest way is to enumerate through values of array and check substrings:
NSArray *array = [NSArray arrayWithObjects: #"1.1 something", #"1.2 something else", #"1.3 out of left field", #"1.4 yet another!", nil];
NSString *str = #"1.33";
int i = -1;
int index = -1;
for (NSString *arrayString in array) {
i++;
if ([arrayString rangeOfString: str].location != NSNotFound) {
index = i;
break;
}
}
NSLog(#"Index: %d", index);
Not optimal but will work.
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.