How to deduce type NSString in NSLog function in Objective-C?

I need login on behalf of the user and output of this input name to NSLog using NSString. I don’t know which% sign and how to display it. Can I use the scanf () function to do this? Please help me, I'm just starting Objective-C.

+7
source share
5 answers

You can use% @ for all objects, including NSString. This, in turn, will call the description method of the objects and print the corresponding line. Most objects already have a pretty useful representation (for example, NSArray objects return descriptions of all their contents).

+23
source

Mark Dylan is the name that will be stored in the Name variable.

 NSString* Name = @"Mark Dylan"; 

This code will allow you to ask for their name and scan it into memory, which will be stored in the Name variable.

 NSLog("What is your name?"); scanf("%@", &Name); 

If you want to print a variable that you can use,

 NSLog("Your name is %@", Name); 
+3
source

%@ is what you want. It is suitable for an object of type NSString , [YourViewController class]

+1
source

NSLog accepts a format string, so you can do something like this:

 #include <stdio.h> #include <Foundation/Foundation.h> // 1024 characters should be enough for a name. // If you want something more flexible, you can use GNU readline: // <http://cnswww.cns.cwru.edu/php/chet/readline/rltop.html> #define MAX_NAME_LENGTH 1024 // Get name from user input char name[MAX_NAME_LENGTH]; name[0] = '\0'; // just in case fgets fails fgets(name, MAX_NAME_LENGTH, stdin); // Put name into NSString object and output it. NSString *name = [NSString stringWithUTF8String:name]; NSLog(@"%@", name); 

%@ works for all Objective-C objects. If you want to print a C string ( char* or const char* ), use %s . Never put a non-literal string as the first argument to NSLog , as this opens up security holes.

+1
source

To access from a user, use UITextField or NSTextField . To output a line to a log file, you can use NSLog, that is:

 NSString* userName = @"Zawmin"; NSLog(@"name = %@", userName); 
0
source

All Articles