Mohd Sadham
Mohd Sadham

Reputation: 435

Why NSLog print like these?

Line of Code:

@interface ViewController (){
IBOutlet UILabel *lbl_FirstName;
IBOutlet UILabel *lbl_LastName;

}

@implementation ViewController

- (void)viewDidLoad
{
[super viewDidLoad];

lbl_FirstName.text=@"XFirst";
lbl_LastName.text=@"XLast";

NSLog(@"First Name: %@",lbl_FirstName.text);
NSLog(@"Last Name: %@ %@",lbl_LastName.text);

}

Result:

First Name: XFirst
Last Name: (null) XLast

Problem: * Why 2nd NSLog statement print like these?

I know the reason of (null), because i didn't give any reference for the lbl_Lastname in my .xib. But I don't know the reason of print after (null).

Upvotes: 1

Views: 318

Answers (4)

codercat
codercat

Reputation: 23301

specifier %@

Objective-C object, printed as the string returned by descriptionWithLocale: if available, or description otherwise. Also works with CFTypeRef objects, returning the result of the CFCopyDescription function.

https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html

Upvotes: 0

GenieWanted
GenieWanted

Reputation: 4513

From the documentation, it says:

In format strings, a ‘%’ character announces a placeholder for a value, with the characters that follow determining the kind of value expected and how to format it.

So, probably, it allocates/announces two placeholders for your string already. And, it finds the value for the first placeholder. Found nothing.. Hence, it shows (null) and finds a value for the second placeholder and prints it accordingly. This should be the case IMHO..

Upvotes: 1

Gajendra Rawat
Gajendra Rawat

Reputation: 3663

hey Why you add more than %@ for more than one variable print value like this.

NSLog(@"Last Name: %@",lbl_LastName.text);

If you are getting null value in console the check your outlet connection

Upvotes: 0

James Webster
James Webster

Reputation: 32066

It appears that the next object in memory happens to be the value of "XLast".

What I speculate happens is:

  • You create a string: @"XLast"
  • The program attempts to assign this value to lbl_LastName.text, but since lbl_LastName is nil, it fails.
  • The NSLog correctly prints out the fact that lbl_LastName.text is ni, but since you have two %@, it also prints out the next object in memory. This happens to be the string: @"XLast" that you just allocated.

This is likely undefined behaviour and it may not act the same every time.

Upvotes: 1

Related Questions