if statement with empty UILabel - ios

I have a UILabel that is loaded form a text file. Sometimes the text file has something in it and sometimes it is empty. So sometimes the UILabel is blank and sometimes it has text in it.
I want to write an if statement that says if the UILabel is blank do one thing else if it has text in it do another thing.
I have tried
if (self.label.text = NULL)
and
if (self.label.text = #"")
but it isn't working correctly.
With the if (self.label.text = #""), I get the if statement to happen but the else statement doesn't work.
Here is my code
NSString *stuff3 = #"/Stuff";
NSString *titleName = [familyDictionary objectForKey:#"identity"];
NSArray *paths3 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory3 = [paths3 objectAtIndex:0];
NSString *stuffPath3 = [documentsDirectory3 stringByAppendingPathComponent:stuff3];
NSString *fullPath3 = [stuffPath3 stringByAppendingPathComponent:titleName];
self.title = [NSString stringWithContentsOfFile:fullPath3 encoding:NSUTF8StringEncoding error:NULL];
NSLog(#"full path 3 >>>%#",fullPath3);
NSString *stuff4 = #"/Stuff/Objects";
NSString *textName3 = [familyDictionary objectForKey:#"identity"];
NSArray *paths2 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory2 = [paths2 objectAtIndex:0];
NSString *stuffPath = [documentsDirectory2 stringByAppendingPathComponent:stuff4];
NSString *fullPath2 = [stuffPath stringByAppendingPathComponent:textName3];
self.wordlabel.text = [NSString stringWithContentsOfFile:fullPath2 encoding:NSUTF8StringEncoding error:NULL];
//Now load the image at fullPath and install it into our image view's image property.
NSLog(#"full path 3 >>>%#",fullPath2);
if(self.wordlabel.text = #"")
{
[textView setTitle:[NSString stringWithContentsOfFile:fullPath3 encoding:NSUTF8StringEncoding error:NULL] forState:UIControlStateNormal] ;
textView.titleLabel.adjustsFontSizeToFitWidth = TRUE;
}
else
{
[textView setTitle:[NSString stringWithContentsOfFile:fullPath2 encoding:NSUTF8StringEncoding error:NULL] forState:UIControlStateNormal] ;
textView.titleLabel.adjustsFontSizeToFitWidth = TRUE;
}

You're doing it wrong, wrong.
Wrong 1: = is the assignment operator, == is the equality operator. You're using the assignment operator inside an if statement, you should at least be getting a compiler warning about that.
Wrong 2: Even if you had that bit right, it's the wrong way to compare strings. Use isEqualToString: or check length as in the other answers.
Wrong 3: The logic should probably be based on the strings before you assign them to the label, not by reading back what is in the label. It's a cleaner MVC implementation.

What you are doing is comparing pointers, which doesn't work with strings. Use this
if ([self.wordlabel.text isEqualToString:#"thestring"])

you should ideally use:
if ([self.label.text length] > 0)

When you say self.label.text = #"" you are changing your label's text. = is the assignment operator. == is the comparison operator.
However, to compare strings, you must use the comparison method [self.label.text isEqualToString:#""], otherwise you are just comparing pointers.

Related

How do I create line breaks in a String I loaded from a textfile

I want to load a simple text, like:
"first \n second"
My code is :
NSString *filePath = [[NSBundle mainBundle] pathForResource:path ofType:#"df"];
NSArray* allLines;
if (filePath) {
NSString* content = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
allLines = [content componentsSeparatedByString:#"#"]; //Of course my text is separate with #
}else{
NSLog(#"%# didnt load", path);
}
for (int i = 0; i < [allLines count]; i++) {
[_textArray addObject:(NSString*)allLines[i]];
NSLog(#"Answer: %#",(NSString*)allLines[i]);
}
And I want to get this text on an UILabel. But I don't know how I can make this line breaks to work. :S
Instead of putting \n in the text file, put actual newlines in the text file. In other words, put "first" and "second" on two separate lines in the text file.
You wanted either of
label.text = [allLines componentsJoinedByString:#"\n"];
label.text = [content stringByReplacingOccurrencesOfString:#"#" withString:#"\n"];
But yes, just putting the newlines in the source file works fine too.

Remove characters before dot

Im parsing html and now i got an NSString object that output like that:
imageName is 4tmp.jpg
imageName is 5tmp.jpg
imageName is 6tmp.jpg
imageName is 7tmp.jpg
imageName is 8tmp.jpg
imageName is 9tmp.jpg
And so on.
My code look like:
TFHpple *dataParseer = [TFHpple hppleWithHTMLData:data];
// 3
NSString *dataXpathQueryString = #"//head/title";
NSArray *dataNodes = [dataParseer searchWithXPathQuery:dataXpathQueryString];
TFHppleElement *element = dataNodes[0];
if ([element.text hasPrefix:#"Index of"]) {
dataXpathQueryString = #"//tr/td/a";
dataNodes = [dataParseer searchWithXPathQuery:dataXpathQueryString];
for (TFHppleElement *element in dataNodes){
NSString *imageName = [element objectForKey:#"href"];
NSLog(#"imageName is %#", imageName);
}
What i want is, remove characters before dot. So i can further concatenate it to correct url. How could i do that with NSString? Is there any method that can check characters before special symbol?
I'm not quite sure what exactly you want to get, but there are several ways to get values from string.
If you are working with path structures you can do something like this.
NSString *path = #"4tmp.jpg";
NSLog(#"1- %#",path.lastPathComponent);
NSLog(#"2- %#",[path.lastPathComponent stringByDeletingPathExtension]);
NSLog(#"3- %#",path.pathExtension);
Which will output something like
1- 4tmp.jpg
2- 4tmp
3- jpg
This will work obviously for more complex paths like "something/4tmp.jpg" in those cases the output will be the same as the one above
NSArray* stringComponents = [imageName componentsSeparatedByString:#"."];
imageName = [stringComponents objectAtIndex:1];

Replace String Between Two Strings

I have a serious problem about indexing in array. I've been working on this for 2 days and couldn't find answer yet.
I want to do that, search specific character in array then replace it with other string. I'm using replaceObjectAtIndex method but my code is doesn't work.
Here is my code;
NSString *commentText = commentTextView.text;
NSUInteger textLength = [commentText length];
NSString *atSign = #"#";
NSMutableArray *commentArray = [[NSMutableArray alloc] init];
[commentArray addObject:commentText];
for (int arrayCounter=1; arrayCounter<=textLength; arrayCounter++)
{
NSRange isRange = [commentText rangeOfString:atSign options:NSCaseInsensitiveSearch];
if(isRange.location != NSNotFound)
{
commentText = [commentText stringByReplacingOccurrencesOfString:commentText withString:atSign];
[_mentionsearch filtrele:_mentionText];
id<textSearchProtocol> delegate;
[delegate closeList:[[self.searchResult valueForKey:#"user_name"] objectAtIndex:indexPath.row]];
}
}
Ok, now i can find "#" sign in the text and i can match it. But this is the source of problem that, i can not replace any string with "#" sign. Here is the last part of code;
-(void)closeList
{
NSArray *arrayWithSign = [commentTextView.text componentsSeparatedByString:#" "];
NSMutableArray *arrayCopy = [arrayWithSign mutableCopy];
[arrayCopy replaceObjectAtIndex:isRange.location withObject:[NSString stringWithFormat:#"#%#",username]];
}
When im logging isRange.location value, it returns correct. But when im try to run, my application is crashing. So, i can not replacing [NSString stringWithFormat:#"#%#",username] parameter. How can i solve this problem?
If I understand correctly you want to change a substring in a string with a new string. In this case, why don't you use directly the stringByReplacingOccurrencesOfString method of NSString:
NSString *stringToBeChanged = #"...";
NSString *stringToBeChangedWith = #"...";
NSString *commentTextNew = [commentText stringByReplacingOccurrencesOfString:stringToBeChanged withString:stringToBeChangedWith];

iphone - app crash in a form

In my app, I have a view where user have to fill a form. But, sometime the app crash here, in this function, that simple cacth the value field and built a url to give
-(NSString*)urlToUpload{
NSString *string1 =[[NSString alloc]init];
string1= [NSString stringWithFormat:#"?nombre="];
NSString *string2 = [string1 stringByAppendingString:nameAdded];
//crash here
NSString *string3 = [string2 stringByAppendingString:#"&horario="];
NSString *string4 = [string3 stringByAppendingString:horarioAdded];
NSString *string5 = [string4 stringByAppendingString:#"&info="];
NSString *string6 = [string5 stringByAppendingString:infoAdded];
NSString *string7 = [string6 stringByAppendingString:#"&offerta="];
NSString *string8 = [string7 stringByAppendingString:offertaAdded];
NSString *lat_string = [[[NSString alloc] initWithFormat:#"%f",locationToUpload2.latitude] autorelease];
NSString *lon_string = [[[NSString alloc] initWithFormat:#"%f",locationToUpload2.longitude] autorelease];
NSString *string9 = [string8 stringByAppendingString:#"&latitude="];
NSString *string10 = [string9 stringByAppendingString:lat_string];
NSString *string11 = [string10 stringByAppendingString:#"&longitude="];
NSString *string12 = [string11 stringByAppendingString:lon_string];
NSString *url1 = [NSString stringWithFormat:#"http://myserverside/mysql_up.php"];
NSString *url = [url1 stringByAppendingString:string12];
return url;
}
EDIT:
It seems problem appers on nameAdded when there is a white space into textField(i.e. MisterB not crash, Mister B yes ).
But I am using:
nameAdded =[[nameField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
and NSLOg give of nameAdded is Mister%20B.
The crash still appearing...
Just use a single stringWithFormat::
- (NSString *)urlToUpload {
NSString *url = [NSString stringWithFormat:#"http://myserverside/mysql_up.php?nombre=%#&horario=%#&info=%#&offerta=%#&latitude=%f&longitude=%f",
[nameAdded stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
[horarioAdded stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
[infoAdded stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
[offertaAdded stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
locationToUpload2.latitude, locationToUpload2.longitude];
return url;
}
Make sure the referenced variables are valid.
In your original code there is no need to alloc/init an NSString then assign another string to the same variable. That's a memory leak (string1).
If you really want to structure your code the way you have it, at least use an NSMutableString and append to that one mutable string. Creating over a dozen NSString variables is the wrong way to do it.
Updated: Ensure each of the strings added to the URL are properly escaped.
It looks like nameAdded may be the cause of your problems. Is it nil at that point?
Also
You are allocating a string, setting it to string1 and then immediately setting string1 to the class function stringWithFormat which allocates another string. Also you are using stringWithFormat but you aren't using any format so you could simply use NSString *string1 = #"?nombre=";
Rather than declaring all of those variables you should just use NSMutableString and build it all in one variabl

Removing last characters of NSString until it hits a separator

I've got a string that shows the stock amount using "-" as separators.
It's built up like this: localStock-wareHouseStock-supplierStock
Now I want to update the supplierStock at the end of the string, but as you can see in the code below it goes wrong when the original string returns more than a single-space value (such as 20).
Is there a way to remove all characters until the last "-" (or remove characters after the second "-")?
NSMutableString *string1 = [NSMutableString stringWithString: p1.colorStock];
NSLog(#"string1: %#",string1);
NSString *newString = [string1 substringToIndex:[string1 length]-2];
NSLog(#"newString: %#",newString);
NSString *colorStock = [NSString stringWithFormat:#"%#-%#",newString,p2.supplierStock];
NSLog(#"colorstock: %#",colorStock);
p1.colorStock = colorStock;
NSLog1
string1: 0-0-0
newString: 0-0
colorstock: 0-0-20
NSLog2
string1: 0-0-20
newString: 0-0-
colorstock: 0-0--20
EDIT: Got it working thanks to Srikar!
NSString *string1 = [NSString stringWithString: p1.colorStock];
NSLog(#"string1: %#",string1);
NSString *finalString = [string1 stringByReplacingOccurrencesOfString:[[string1 componentsSeparatedByString:#"-"] lastObject] withString:p2.supplierStock.stringValue];
NSLog(#"finalString: %#",finalString);
p1.colorStock = finalString;
Why not use componentsSeparatedByString followed by lastObject ?
NSString *supplierStock = [[string1 componentsSeparatedByString:#"-"] lastObject];
The above works if the "stock amount" is always in sets of 3's separated by a "-". Also since you always want supplierStock, lastObject is perfect for your needs.
Of course after splitting string1 with - you get a NSArray instance and you can access the individual components using objectAtIndex:index. So if you want localStock you can get by
NSString *localStock = [[string1 componentsSeparatedByString:#"-"] objectAtIndex:0];
I would suggest splitting the string into the 3 parts using [NSString componentsSeparatedByString:#"-"] and then building it back up again:
NSArray *components = [p1.colorStock componentsSeparatedByString:#"-"];
p1.colorStock = [NSString stringWithFormat:#"%#-%#-%#",
[components objectAtIndex:0],
[components objectAtIndex:1],
p2.supplierStock];
With a string that looks like
NSString *myString = #"Hello-World";
you can separate it with the componentsSeparatedByString: method of the NSString object as
NSArray *myWords = [myString componentsSeparatedByString:#"-"];
The myWords - array will then contain the two NSString objects Hello and World.
To access the strings:
NSString *theHelloString = [myWords objectAtIndex:0];
NSString *theWorldString = [myWords objectAtIndex:1];
Hope it helps!
None of these examples show how to do this if you are unaware of how many of these separator occurrences you're going to have in the original string.
Here's what I believe the correct the correct code should be for dismantling the original string and rebuilding it until you reach the final separator, regardless of how many separators it contains.
NSString *seperator = #" ";
NSString *everythingBeforeLastSeperator;
NSArray *stringComponents = [originalString componentsSeparatedByString:seperator];
if (stringComponents.count!=0) {
everythingBeforeLastSeperator = [stringComponents objectAtIndex:0];
for (int a = 1 ; a < (stringComponents.count - 1) ; a++) {
everythingBeforeLastSeperator = [NSString stringWithFormat:#"%#%#%#", everythingBeforeLastSeperator, seperator, [stringComponents objectAtIndex:a]];
}
}
return everythingBeforeLastSeperator;

Resources