Using NSLog for debugging - objective-c

I have the following code snippet in my Xcode:
NSString *digit [[sender titlelabel] text];
NSLog([digit]);
I tried to build the application and am getting the following warning message for the line NSLog([digit]);
Warning: Format not a string literal and no format arguments
Can you advise me how I can resolve this warning message? What does the message actually mean?

Try this piece of code:
NSString *digit = [[sender titlelabel] text];
NSLog(#"%#", digit);
The message means that you have incorrect syntax for using the digit variable. If you're not sending it any message - you don't need any brackets.

Use NSLog() like this:
NSLog(#"The code runs through here!");
Or like this - with placeholders:
float aFloat = 5.34245;
NSLog(#"This is my float: %f \n\nAnd here again: %.2f", aFloat, aFloat);
In NSLog() you can use it like + (id)stringWithFormat:(NSString *)format, ...
float aFloat = 5.34245;
NSString *aString = [NSString stringWithFormat:#"This is my float: %f \n\nAnd here again: %.2f", aFloat, aFloat];
You can add other placeholders, too:
float aFloat = 5.34245;
int aInteger = 3;
NSString *aString = #"A string";
NSLog(#"This is my float: %f \n\nAnd here is my integer: %i \n\nAnd finally my string: %#", aFloat, aInteger, aString);

Why do you have the brackets around digit?
It should be
NSLog("%#", digit);
You're also missing an = in the first line...
NSString *digit = [[sender titlelabel] text];

The proper way of using NSLog, as the warning tries to explain, is the use of a formatter, instead of passing in a literal:
Instead of:
NSString *digit = [[sender titlelabel] text];
NSLog(digit);
Use:
NSString *digit = [[sender titlelabel] text];
NSLog(#"%#",digit);
It will still work doing that first way, but doing it this way will get rid of the warning.

type : BOOL
DATA (YES/NO) OR(1/0)
BOOL dtBool = 0;
OR
BOOL dtBool = NO;
NSLog(dtBool ? #"Yes" : #"No");
OUTPUT : NO
type : Long
long aLong = 2015;
NSLog(#"Display Long: %ld”, aLong);
OUTPUT : Display Long: 2015
long long veryLong = 20152015;
NSLog(#"Display very Long: %lld", veryLong);
OUTPUT : Display very Long: 20152015
type : String
NSString *aString = #"A string";
NSLog(#"Display string: %#", aString);
OUTPUT : Display String: a String
type : Float
float aFloat = 5.34245;
NSLog(#"Display Float: %F", aFloat);
OUTPUT : isplay Float: 5.342450
type : Integer
int aInteger = 3;
NSLog(#"Display Integer: %i", aInteger);
OUTPUT : Display Integer: 3
NSLog(#"\nDisplay String: %# \n\n Display Float: %f \n\n Display Integer: %i", aString, aFloat, aInteger);
OUTPUT :
String: a String
Display Float: 5.342450
Display Integer: 3
http://luterr.blogspot.sg/2015/04/example-code-nslog-console-commands-to.html

NSLog(#"%#", digit);
what is shown in console?

NSLog([digit]); // [] are the messages in Objective-C, just like methods or functions in other programming languages
Since you just need to print the value of 'digit'
Either you can call -
NSLog(digit); // A warning would occur - Format string is not a string literal (potentially insecure)
OR
NSLog(#"%#",digit]); // But if you use %# to reference the object, the warning will go away.
Both the methods will work but the second one is the right way of logging to console.

Related

Making a backspace button for a calculator

I am making an iOS calculator and it I'm having minor difficulties with the backspace button (for deleting the last number of the value displayed on a label).
To get the current value on the label I use
double currentValue = [screenLabel.text doubleValue]
Following other questions, I tried something like
-(IBAction)backspacePressed:(id)sender
{
NSMutableString *string = (NSMutableString*)[screenLabel.text];
int length = [string length];
NSString *temp = [string substringToIndex:length-1]
;
[screenLabel.text setText:[NSString stringWithFormat:#"%#",temp]];
}
But it does not work,
(Xcode says "setText is deprecated", "NSString may not respond to setText" and that an identifier is expected in the first line of code inside the IBAction)
and I do not really understand this code to make it work by myself.
What should I do?
It should be
[screenLabel setText:[NSString stringWithFormat:#"%#",temp]];
Your Xcode clearly says that you are trying to call setText' method on anNSStringwhere as you should be calling that on aUILabel. YourscreenLabel.textis retuning anNSString. You should just usescreenLabelalone and should callsetText` on that.
Just use,
NSString *string = [screenLabel text];
The issue with that was that, you are using [screenLabel.text]; which is not correct as per objective-c syntax to call text method on screenLabel. Either you should use,
NSString *string = [screenLabel text];
or
NSString *string = screenLabel.text;
In this method, I dont think you need to use NSMutableString. You can just use NSString instead.
In short your method can be written as,
-(IBAction)backspacePressed:(id)sender
{
NSString *string = [screenLabel text];
int length = [string length];
NSString *temp = [string substringToIndex:length-1];
[screenLabel setText:temp];
}
As per your question in comments(which is deleted now), if you want to display zero when there are no strings present, try,
-(IBAction)backspacePressed:(id)sender
{
NSString *string = [screenLabel text];
int length = [string length];
NSString *temp = [string substringToIndex:length-1];
if ([temp length] == 0) {
temp = #"0";
}
[screenLabel setText:temp];
}

changing a string to double returning one

I have stored a value 1/129600.0 in a plist as a string.
I am able to retrieve it as a string but when i am trying to convert it as a double i am getting it as 1.0.I have also tried CFString
NSString *value = [[self array]objectAtIndex:m];
double a = [value doubleValue];
NSLog(#"%#",value);
NSLog(#"%f",a);
and in log the returned values are
1/129600.0 and 1.0
This code works fine, I tried it in xCode:
NSString *equation = [[self array]objectAtIndex:m];
NSExpression *result = [NSExpression expressionWithFormat:equation];
NSNumber *a = [result expressionValueWithObject:nil context: nil];
NSLog(#"%#",result);
NSLog(#"%.10f",[a doubleValue]);
I guess 1/129600.0 is not a valid number.
Try to create an expression and create an NSNumber from it:
NSString *equation = [[self array]objectAtIndex:m];
NSNumber *a = [[NSExpression expressionWithFormat:equation] expressionValueWithObject:nil context:nil];
double a = [result doubleValue];
NSLog(#"%f", a);
1/129600.0 is not a valid representation for a number in most programming languages, including ObjC. You need to parse the string and interpret it yourself.
Try this
NSString *value = [[self array]objectAtIndex:m];
NSArray *arr = [value componentsSeparatedByString:#"/"];
double a;
if ([arr count] == 2)
{
a = [arr objectAtIndex:0]/[arr objectAtIndex:1];
}
NSLog(#"%#",value);
NSLog(#"%f",a);

Objective-C: Receive "EXC_BAD_ACCESS" signal [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
EXC_BAD_ACCESS when trying to get iPhone screen dimensions
I have the following code snippet in objective-c that automatically sets some variables to a number of presets. However, on the marked line I get a "Program received signal: EXC_BAD_ACCESS" exception.
What confuses me is that the line above is identical, just with a different value. If line 1 does not throw an exception, why should line 2? What can I do about this?
Thanks in advance!
Sterren
- (IBAction)presetPressed:(id)sender {
if(self.userEnteringNumber) [self enterPressed];
double xVal;
double aVal;
double bVal;
NSString *preset = [sender currentTitle];
if ([preset isEqualToString:#"1"]) {
xVal = 1;
aVal = 2;
bVal = 3;
} else if ([preset isEqualToString:#"2"]) {
xVal = 1.5;
aVal = 2.9;
bVal = 3.0;
} else if ([preset isEqualToString:#"3"]) {
xVal = -1;
aVal = -2;
bVal = -3;
}
[self.variables setValue:[NSNumber numberWithDouble:xVal] forKey:#"x"];
[self.variables setValue:[NSNumber numberWithDouble:aVal] forKey:#"a"];
[self.variables setValue:[NSNumber numberWithDouble:bVal] forKey:#"b"];
self.xVar.text = [NSString stringWithFormat:#"= %#", xVal];
self.aVar.text = [NSString stringWithFormat:#"= %#", aVal]; //EXC_BAD_ACCESS here
self.bVar.text = [NSString stringWithFormat:#"= %#", bVal];
[self calculateResult];
}
xVal, aVal, bVal are all primitive doubles, but yet your string format is looking for an object via %#.
try replacing %# with %f (or %g if you prefer scientific notation):
self.xVar.text = [NSString stringWithFormat:#"= %f", xVal];
self.aVar.text = [NSString stringWithFormat:#"= %f", aVal];
self.bVar.text = [NSString stringWithFormat:#"= %f", bVal];
Replace your formatting strings #"= %#" with #"= %g".
Your formatting string was assuming that the given parameter value would be an object instance (%#) but you supplied a scalar double value which is not an object instance but of a primitive type.

Convert float value to NSString

Do you know how can i convert float value to nsstring value because with my code, there is an error.
My Code :
- (float)percent:(float)a :(float)b{
return a / b * 100;
}
- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects {
// ....
float tx_nb_demande_portabilite = [self percent: [(NSNumber*) [stat nb_demande_portabilite] floatValue] :[(NSNumber*) [stat nb_users] floatValue]];
NSString *tx_nb_demande_portabilite_st = [NSString stringWithFormat:#"%#", tx_nb_demande_portabilite];
//....
}
The error :
EXC_BAD ACCESS for NSString *tx_nb_demande_portabilite_st = [NSString stringWithFormat:#"%#", tx_nb_demande_portabilite];
Thank you for your help.
You need to use %f format specifier for float, not %#.
NSString *str = [NSString stringWithFormat:#"%f", myFloat];
To use specific number of digits after decimal use %.nf where n is number of digits after decimal point.
// 3 digits after decimal point
NSString *str = [NSString stringWithFormat:#"%.3f", myFloat];
Obj-C uses C printf style formatting. Please check printf man page for all other possible formatting.
one more option:
NSString * str = [NSNumber numberWithFloat:value].stringValue;
#"%f" sounds like more appropriate format string for float.
[NSString stringWithFormat:#"%f", tx_nb_demande_portabilite];
A modern (and less verbose) approach would be:
NSString *str = #(myFloat).description;

How to use combination of text and variables in NSString?

How would I use a combination of text and variables in a NSString?
I know that in an NSLog, it looks like this:
int number = 5;
NSLog(#"My favorite number is %i", number);
How would I go about doing something like that in an NSString or even a char variable?
That is fairly simple:
NSString *string = [NSString stringWithFormat:#"My favorite number is %i", number];
its basically the same as nslog.
NSString * str = [NSString stringWithFormat:#"My favorite number is %i", number];
if you just want to read about format specifiers, see: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html
use all the power of old beloved printf formatting.
for objects "%#" will call the description method, so be smart to write this method for every custom class:
-(NSString*)description;
{
NSString* result = [NSString stringWithFormat(#"%#" .......
}
for example:
-(NSString *)description;
{
return [NSString stringWithFormat:#"is: %# %# %# ; at: %f %f",
name, address, img_name,
coord.latitude, coord.longitude];
}