UILabel.text doesn't change from NSString (iOS) - ios

I'm trying to change name(UILabel).text to nameString(NSString) but it does not present it on the screen (it does change - is it the value when I debug and it the correct value).
Code:
NSString *namesString = [self.names objectAtIndex:i];
infoWindow.storeAddressLabel.text = namesString;
Note: if I type:
infoWindow.storeAddressLabel.text=#"someText";
It works
Does anybody know why is it? Thanks!

You're referencing two different variables. On the 1st line you define nameString, and then on the next line you set using namesString with an extra s

If infoWindow.storeAddressLabel.text=#"someText"; works, then storeAddressLabel object isn't nil. The only possibility can be that the string being returned from the code NSString *namesString=[self.names objectAtIndex:i]; is being returned nil. Please check and verify.
Thanks.

Try this see what happens,
NSString *nameString=[sef.names objectAtIndex:i];
if( nameString!=nil && nameString.length >0){
NSLog(#"nameString %#",nameString);
infoWindow.storeAddressLabel.text=namesString;
}
else{
infoWindow.storeAddressLabel.text=#"nameString variable was nil so I am being set as label text";
}

In correction to above code which contains many bugs, i have written following answer:
NSString *nameString = [sef.names objectAtIndex:i];
if(nameString)
{
infoWindow.storeAddressLabel.text = nameString;
}
else
{
infoWindow.storeAddressLabel.text = #"nameString variable was nil so I am being set as label text";
}

Try using a class method to assign the text property - (check for nil first of course as stringWithString: must be passed a non-nil NSString)
infoWindow.storeAddressLabel.text = [NSString stringWithString:(NSString*)[self.names objectAtIndex:i]];

If your namesString is not nil then it should be displayed..
try like this,
NSString *namesString = [self.names objectAtIndex:i];
infoWindow.storeAddressLabel.text = [NSString stringWithFormat:#"%#",namesString];

Related

Comaparing NSString in Objective C

Any one please help me to understand the String comparison technique in Objective-C
NSString *strNew1 = #"AA";
NSString *strNew2 = #"AA";
So to compare both the strings we could use,
Method 1. if (strNew1 == strNew2) {
NSLog(#"Equal");
}
or
Method 2: if ([strNew1 isEqualToString:strNew2]) {
NSLog(#"Equal");
}
In this condition both of them are success. But am aware that method 1 will get failed at certain other condition. And also I have tried the below conditions(All are success).
NSString *strNew = #"AA";
NSString *strNew1 = #"AA";
NSString *strNew11 = [[NSString alloc] initWithString:strNew1];
NSString *strNew3 = strNew;
NSArray *arr = #[#"AA"];
NSString *strNew4 = [arr objectAtIndex:0];
NSString *strNew5 = [arr objectAtIndex:0];
_test = strNew5;
_test1 = #"AA";
if ([strNew isEqualToString:strNew1]) {
NSLog(#"Equal");
}
if (strNew == strNew3) {
NSLog(#"Equal1");
}
if (strNew == [arr objectAtIndex:0]){
NSLog(#"Equal2");
}
if (strNew == strNew4){
NSLog(#"Equal3");
}
if (strNew5 == strNew4){
NSLog(#"Equal4");
}
if (strNew4 == [arr objectAtIndex:0]){
NSLog(#"Equal5");
}
if (strNew11 == [arr objectAtIndex:0]){
NSLog(#"Equal11");
}
if (self.test == strNew4){
NSLog(#"Equal3");
}
if (self.test == self.test1){
NSLog(#"Equal3");
}
TEST *test = [TEST new]; // Tried with a class with NSString property with value "AA" . (test.strTest value is #"AA")
if (strNew == test.strTest) {
NSLog(#"Equal"); //success
}
I knew most of them are redundant. Am not able to understand the basics behind this. Please anyone give clear explanation on the concept behind this. Thanks.
In the cases you defined the strings created are internally treated as string literals. The runtime will not allocate different memory space to such strings.
Essentially all the strings that contain the same string literal ("AA" in your case) will point to the same memory location. This is done as a part of memory optimization by Apple.
When you change the value of any string (say to "AB") a new address will be allocated to that NSString object and then == will fail.
You need to use below instance method of NSString class.
- (BOOL)isEqualToString:(NSString *)aString;
So, In your case simply follow below:
if ([strNew isEqualToString strNew4]){
NSLog(#"Equal3");
}
By doing (strNew == strNew4),
You are only comparing the addresses of the objects.
The first way compares pointers, while the second way compares objects.
That is, the first way compares if the pointers have the same value. In this case it is likely that they don't, in the second case the objects will be compared. Since they are initialized the same way they could be equal. (Note, it appears that with the UIButton's implementation of isEqual: the result is always false.)
In most cases using == is not what you want. However, what is appropriate depends on your objective.
if (strNew1 == strNew2) //This compared your pointers
{
}
and
if ([strNew1 isEqualToString:strNew2]) //Compares NSString object
{
}
Remember that isEqualToString: comes with a WARNING
[string1 isEqualToString: string2]
will effectively return false is both strings are nil.

Trying to Track Down Where JSON Dictionary Value Needs to Be Implemented iOS

I have the following method which is creating a URL to an image:
-(NSURL*)urlForImageWithId:(NSNumber*)IdPhoto isThumb:(BOOL)isThumb {
NSString* urlString = [NSString stringWithFormat:#"%#/%#upload/%#%#.jpg",
kAPIHost, kAPIPath, IdPhoto, (isThumb)?#"-thumb":#""
];
return [NSURL URLWithString:urlString];
}
I need to update the path to include the IdUser value that is associated with said image. Here is the way that I have attempted this:
-(NSURL*)urlForImageWithId:(NSNumber*)IdPhoto isThumb:(BOOL)isThumb {
NSString* urlString = [NSString stringWithFormat:#"%#/%#upload/%#/%#%#.jpg",
kAPIHost, kAPIPath, IdUser, IdPhoto, (isThumb)?#"-thumb":#""
];
return [NSURL URLWithString:urlString];
}
When I tried to do this, xcode says “Declare IdUser,” so I did. I Added this to the .h
#property (assign, nonatomic) NSNumber* IdUser;
and I added this below implementation:
#synthesize IdUser;
but when I run the program I get a null value for IdUser.
When I log the dictionary like this:
NSLog(#"Result from Stream: %#",json);
I get the following output:
result = (
{
IdPhoto = 5;
IdUser = 7;
title = this is the title;
username = presto;
});
}
as one example. Here you can clearly see that the IdUser value is being passed through the dictionary. My guess is that the IdPhoto from -(NSURL*)urlForImageWithId:(NSNumber*)IdPhoto isThumb:(BOOL)isThumb {
must be defined somewhere else. Any idea on what I should look for to track this down and be able to pull that IdUser value over as well?
Just adding a property does not set the value of that property. Where is self.IdUser being initiated? It sounds like you are confusing a key of a dictionary with a ViewController property.
Try this to see if that is the case (do this after you get that NSArray named json).
NSDictionary *dict = [json objectAtIndex:0];
self.IdUser = [dict objectForKey:#"IdUser"];
NSLog(#"self.IdUser = %#", self.IdUser];
if idUser is an instance variable, you need to write it as _IdUser or self.IdUser.
Also try: [_idUser stringValue] inside the NSString stringWithFormat method to get the correct type as you specified it as a string ("#").

IF statement issue in IOS using NSString

My if statement won't work. active returns 1 but will not work in the IF statement
JSONDecoder *jsonKitDecoder = [JSONDecoder decoder];
NSDictionary *dict = [jsonKitDecoder objectWithData:jsonData];
NSString *userid = [dict valueForKeyPath:#"users.user_id"];
NSString *active = [dict valueForKeyPath:#"users.active"];
NSLog(#"%#",userid); // 2013-06-20 03:03:21.864 test[81783:c07] (74)
NSLog(#"%#",active); // 2013-06-20 03:03:21.864 test[81783:c07] (1)
if ([active isEqualToString:#"1"]){
// Do something
}
I can't seem to get this IF to work. Do I need to change the NSString to a int?
For starters, use a modern style for retrieving values from dictionaries, rather than valueForKeyPath:.
NSDictionary* users = dict[#"users"];
id active = users[#"active"];
Once you're using a modern style, my guess is that the active value is actually an NSNumber representing a boolean value. So your if block would read:
if([active isKindOfClass:NSNumber] && [active boolValue]) {
//active is an NSNumber, and the user is active
}
The syntax of your if statement is just fine. I would try the alternate method for retrieving values from a dictionary as mentioned above.
NSString *active = #"1";
if ([active isEqualToString:#"1"])
{
// Do something
NSLog(#"It works!");
}
More than likely the "users.active" object being returned from that NSDictionary-ized JSON stream is a "BOOL" or a "NSInteger" as the payload of a NSNumber object and it's not a NSString object.
Try using:
NSNumber * activeNumber = [dict valueForKeyPath: #"users.active"];
and see if "if ([activeNumber boolValue] == YES)" works better for you.

How to better initialize strings to avoid dead stores

I found a few questions like this but I couldn't find this particular question. I have a number of strings that are initialized as
NSString *string = [[NSString alloc] init];
which are then assigned a value depending on the results of an if/else block:
if ([anotherThing isEqualToString:#"boogers"]) {
string = [NSString stringWithFormat:#"some characters"];
} else {
string = [NSString stringWithFormat:#"some _other_ characters"];
}
and then string is used later in the method.
How can I accomplish this without leaving a dead store at the alloc/init stage? If I alloc inside the if (or the else), the string is gone by the time I need it several lines down.
You don't have to initialize the string on that first line -- you just need to declare it:
NSString *string = nil;
if ([anotherThing isEqualToString:#"boogers"]) {
string = #"some characters";
} else {
string = #"some _other_ characters";
}
The [NSString stringWithFormat:] will initialize a new NSString object for you, basically what you are doing is declaring a new object each time, just set the pointers for your strings as NSSTring *someString, *someOtherString, *allTheStringsYouNeed; and then use any class method to initialize it even #"Characters"; will work correctly as the compiler do it at runtime for you.

How can I access one value among some values

{
"id"=12
"genres_en" = "thriller,movies,action";
}
{
"id"=13
"genres_en" = "thriller,horror";
}
Hi everyone ,
I have one json like this..I mean i have one content and all movie has their genre ..And i need to do one categorization ..For example I need to check which genre of movie is horror..Or which one is thriller..I m getting all value like this:
--> "horror,movies"
But how can i do the controllation to check whether the genre of this movie includes horror or not..??what is your suggesstion?
Thank you
You could use componentsSeparatedByString
NSDictionary *dic = PARSE The JSON;
NSString *values = [dic objectForKey:"genres_en"];
NSString *firstValue = [[values componentsSeparatedByString:","] objectAtIndex:0];
I don't have Xcode nearby, so the following code may contain an error(or two :) ).
Try it like that:
NSDictionary *yourDict = //your parsed json
NSString *genres = [yourDict objectForKey:#"genres_en"];
if ([genres rangeOfString:#"horror"].location != NSNotFound) {
return YES;
} else {
return NO;
}
Hope it helps
for(int j=0;j< GenresArray.count; j++)
{
NSString *value=[[genre componentsSeparatedByString: #","]objectAtIndex:j];
if([value isEqualToString:#"movies"])
{
[genreMovies addObject:value];
}
}
Thank you for your help guys ..Now i have my result:)
You can try to check if the string contains the substring you want . Like this:
NSString *typesString = [dic objectForKey:"genres_en"];
NSRange range = [typesString rangeOfString:#"horror"];
if(range.location != NSNotFound)
{
//it contains the substring "horror"
}
Or , the better way would be to get the array of types.
NSArray *types = [[typesString componentsSeparatedByString:","];
Now you can store this array for each entry and whenever you want to check if it belongs to a certain gender , just loop through the types array ( of each entry ) and compare the strings.
Hope this helps.
Cheers!

Resources