NSString comparison not working [duplicate] - iphone

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
IF clause is not validating NSString function return?
what I am trying to do is get items from an RSS feed and store them in arrays depending on their type. But the problem is when I compare the strings to separate the items nothing happens I have checked and the strings are exactly the same but it says they are not equal.
- (void)parserDidEndDocument:(NSXMLParser *)parser {
if (eventsList != nil) {
for (int i = 0; i<[eventsList count]; i++) {
NSMutableString* str = [[eventsList objectAtIndex:i] objectForKey:#"category"];
if ([str isEqualToString:#"normal"]) {
normalEvents = [[NSMutableArray alloc] init];
[normalEvents addObject:eventsList];
} else if ([str isEqualToString:#"sub"]) {
subEvents = [[NSMutableArray alloc] init];
[subEvents addObject:eventsList];
} else if ([str isEqualToString:#"main"]) {
NSLog(#"salve mundi");
mainEvents = [[NSMutableArray alloc] init];
[mainEvents addObject:eventsList];
} else {
NSLog(#"%#",str);
}
}
}
}

Using == you compare the objects' address. To compare the contents of two NSStrings you have to use the instance method [str isEqualToString:#"sub"] instead.

I would do some tests to ensure that the string is equal. For example, if it has whitespaces at the end or beginning, if it's uppercase, etc..
[[yourString lowercaseString] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]

if([str isEqualToString:#"normal"])

Related

NSMutableArray Not Retaining Objects Outside Method [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
In my -viewDidLoad method, I initialize many NSMutableDictionaries, and add them to an initialized NSMutableArray declared via #property in the class header file. The relevant code is shown below. In short, I'm webscraping information from an HTML webpage.
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
_regionalDicts = [[NSMutableArray alloc] init];
for (int i = 0; i < [strings count]; i++) {
NSString *str = [strings objectAtIndex:i];
//Property parser:
if ([str rangeOfString:#"<td>"].location != NSNotFound) {
NSString *parsedTD1 = [str stringByReplacingOccurrencesOfString:#"<td>" withString:#""];
NSString *parsedTD2 = [parsedTD1 stringByReplacingOccurrencesOfString:#"</td>" withString:#""];
NSString *parsedTD3 = [parsedTD2 stringByReplacingOccurrencesOfString:#" " withString:#"\n"];
NSString *final = [parsedTD3 stringByReplacingOccurrencesOfString:#"\t" withString:#""];
//NSLog(#"Final string: %#", final);
if ([final isEqualToString:#""]) {
continue;
}
if (gotEventType == NO) {
gotEventType = YES;
[dict setObject:final forKey:#"type"];
continue;
}
if (gotRegional == YES && gotLocation == NO) {
gotLocation = YES;
[dict setObject:final forKey:#"location"];
continue;
}
if (gotLocation == YES && gotCity == NO) {
gotCity = YES;
NSString *cityToReturn = [final stringByReplacingOccurrencesOfString:#"\n" withString:#""];
[dict setObject:cityToReturn forKey:#"city"];
continue;
}
if (gotRegional == YES && gotEventType == YES && gotCity == YES && gotLocation == YES && gotURL == YES) {
gotRegional = NO;
gotEventType = NO;
gotCity = NO;
gotLocation = NO;
gotURL = NO;
NSLog(#"Regional: %#", [dict objectForKey:#"regional"]);
NSLog(#"Type: %#", [dict objectForKey:#"type"]);
NSLog(#"City: %#", [dict objectForKey:#"city"]);
//Testing to see if anything is nil
NSLog(#"Location: %#\n", [dict objectForKey:#"location"]);
if (!_regionalDicts) {
NSLog(#"Dict is nil");
}
[_regionalDicts addObject:dict];
NSLog(#"Objects in array: %u", [_regionalDicts count]);
NSMutableDictionary *tempDict = [_regionalDicts objectAtIndex:[_regionalDicts count]-1];
NSLog(#"Regional in array: %#", [tempDict objectForKey:#"regional"]);
[dict removeAllObjects];
continue;
}
It's clear that the generated dictionaries are generated and retained within the _regionalDicts mutable array, which is declared in the header file like this:
#property (strong, nonatomic) IBOutlet NSMutableArray *regionalDicts;
However, when I attempt to pass in information to table view cells in in the same class, the dictionaries' contents are null. There are as many objects within the array as dictionaries I am expecting, but they do not contain any content.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if (_regionalDicts) {
NSMutableDictionary *dict = [_regionalDicts objectAtIndex:0];
NSLog(#"Setting label %#", [dict objectForKey:#"city"]);
[cell.textLabel setText:[dict objectForKey:#"regional"]];
}
return cell;
}
Returns:
2013-04-01 19:58:50.250 MatchScrape[53570:207] Setting label (null)
I can only imagine that a memory management issue is to blame. Why would the contents of a class array be nullified when accessed outside the scope of the method they are added in, but allow the array to retain the same count?
You seem to believe that adding the dictionary to the array doesn't actually add the dictionary to the array, but instead adds a copy of the dictionary. You're probably thinking of how it might work in a language like C++ — but that isn't how it works here. Remember, Objective-C objects are always accessed by reference: you never directly store the object itself in a variable or array — you're just shuffling around a pointer to the actual object, which usually lives on the heap.
So when you add _dict to the array, the one in the array is the very same object referenced by _dict. Anything you do to that dictionary — no matter what reference you use — will be reflected everywhere else that dictionary is referenced, because it's the same dictionary. You haven't made a copy of it. Thus, when you do [_dict removeAllObjects], that removes all the objects from the dictionary and you end up with an array that contains the same empty dictionary a bunch of times.

Tread 9: EXC_BAD_ACCESS [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I get this message "Tread 9: EXC_BAD_ACCESS (code=1, address=0x70000010) in this method (but this bug is being created only when in another thread file is being downloaded ):
- (NSMutableDictionary *) getDictionaryAllStatin:(sqlite3*)database
{
if (self._streetsArrey == nil || self._streetsArrey.count <= 0) {
[self getArrayAllStatin:database];
}
/*--------------------------------------------------------------*/
NSMutableDictionary *result1 = [[NSMutableDictionary alloc] init];
for (StreetData *street in _streetsArrey) {
NSString * name = [self deleteContractionWithText:street._name];
NSArray * arr = [name componentsSeparatedByString:#" "];
NSMutableArray *arrm = [[NSMutableArray alloc] initWithArray:arr];
arr = nil;
[arrm addObject:name];
for (NSString *txt in arrm) {
int lengthText = txt.length;
for (int i = 2 ; i <= lengthText; i++) {
NSString * key = [txt substringToIndex:i];
key = [key lowercaseString];
NSMutableDictionary *isSet = [result1 objectForKey:[NSNumber numberWithInt:[key hash]]];
if (isSet == nil) {
isSet = [[NSMutableDictionary alloc]init];
}
[isSet setObject:street forKey:[NSNumber numberWithInt:street._streetId]];
[result1 setObject:isSet forKey:[NSNumber numberWithInt:[key hash]]];
isSet = nil;
key = nil;
}
}
}
NSMutableDictionary *result = [[NSMutableDictionary alloc] init];
for (id key in result1) {
NSMutableDictionary *dictionary = [result1 objectForKey:key];
NSArray *arr = [dictionary allValues];
[result setObject:arr forKey:key];
arr = nil;
[dictionary removeAllObjects];
dictionary = nil;
}
[result1 removeAllObjects];
result1 = nil;
/*--------------------------------------------------------------*/
if (result.count > 0) {
_streetsDictionary = result;
result = nil;
return _streetsDictionary;
}else {
_streetsDictionary = nil;
return nil;
}
}
Why do I get this message?
How can I fix it?
The most likely cause for the crash is trying to access an object that has already been deallocated.
Since it seems that the failure arises on the line:
NSMutableDictionary *isSet = [result1 objectForKey:[NSNumber numberWithInt:[key hash]]];
I would suggest splitting the statement down to its component to try and track down which object could actually be the culprit:
NSInteger h = [key hash];
NSNumber n = [NSNumber numberWithInt:h];
...
but this bug is being created only when in another thread file is being downloaded
Also, check if the downloading code and the crashing code have anything in common. The former might be causing the deallocation of an object used in the second.
Hope it helps.

sqlite search in multiple column

I have a simple database in iPad Application having couple of tables.
The UI displays the table data properly in a master-detail view controller. I want to add a search feature which will search for the given text in all the field/columns of all the tables and give the result.
One crude way is to write a select query using where clause for each columns. But I believe there will be some proper way for that.
Or is it possible to search the UITableView itself and refresh the data ?
Regards,
nirav
Code for searching in Table
- (void) searchTableView {
NSString *searchText = searchBar.text;
if([searchText length] == 0)
{
[searchArr addObjectsFromArray:userArr];
}
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
for (int i=0; i<[userArr count]; i++) {
NSString *sTemp = [[userArr objectAtIndex:i] objectForKey:#"name"];
NSRange titleResultsRange = [[sTemp lowercaseString] rangeOfString:[searchText lowercaseString]];
if(titleResultsRange.location != NSNotFound && titleResultsRange.location == 0)
{
[searchArr addObject:[userArr objectAtIndex:i]];
}
}
searchArray = nil;
}

how to converts NSMutableArray values into NSString? [duplicate]

This question already has answers here:
How can I convert NSMutableArray into NSString?
(3 answers)
Closed 9 years ago.
hi all how to convert NSMutableArray values into the NSString
when i did as like
Webservices *details=[[Webservices alloc] init];
[details getMobileNumberDetails:phnotextfield.text];
NSLog(#"longitudes Arrays from %#",details.resultData);
"-91.57696007",
"10.343234",
"74.982343",
"76.464844",
"76.464844",
"2.256",
but when implemented like this
theCoordinate2.longitude = [[details.longarray objectAtIndex:0] floatValue];
NSLog(#"longitudes list from %#",theCoordinate2.longitude);
-91.57696007
but my intention is to assign all values to theCoordinate2.longitude so help me to store into string element in iphone.
You can use this code:
theCoordinate2.longitude = [[details.longarray objectAtIndex:0] stringByAppendingString:[details.longarray objectAtIndex:1];
//and so on for index 2,3,4 stringByAppendingString:[details.longarray objectAtIndex:2
NSLog(#"longitudes list from %f",theCoordinate2.longitude);
+1 to Wasif, but while he was composing his answer I was composing my own version of the code you could try:
NSMutableArray * longitudeArray = NULL;
NSString * detailsAsString = details.resultData;
if(detailsAsString)
{
NSArray * longitudeStringArray = [detailsAsString componentsSeparatedByString, #","];
if(longitudeStringArray && ([longitudeStringArray count] > 0))
{
longitudeArray = [[NSMutableArray alloc] initWithCapacity: [longitudeStringArray count]];
if(longitudeArray)
{
for(NSString * longitudeString in longitudeStringArray)
{
[longitudeArray addObject: [NSNumber numberWithFloat: [longitudeString floatValue]]];
}
}
} else {
NSLog( #"did not extract an array out of webservice data");
}
}

How to sort an array with alphanumeric values?

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