arik
arik

Reputation: 29350

Objective C initWithNibName

I am facing some difficulties figuring out what this function in the Apple tutorials stands for:

[[MyViewController alloc] initWithNibName:@"MyViewController" bundle:[NSBundle mainBundle]]

My questions are: what does the "@" stand for before MyViewController?

Addionally, as I am following this tutorial, I was wondering: There are to nibs in my project: the automatically generated MainWindow.xib and MyViewController.xib – I was wondering: why do I have two if I only need one?

Thanks in advance!

Upvotes: 1

Views: 4266

Answers (1)

user142019
user142019

Reputation:

The @-sign before a string literal means that the string is an instance of NSString.

@"Hello" <-- NSString object
"Hello"  <-- Null-terminated char array (C-string)

You can even send messages to it:

[@"Hello" stringByAppendingString:@" World!"]

You will use NSString objects more often than C-strings.

If you want to convert a C-string to an NSString object (if you are using C libraries that return such strings for example), you could use this:

char *myCstring = "Hello, World!";
NSString *myString = [NSString stringWithUTF8String:myCstring];

About the two nibs: actually you don't need any nibs at all, but Apple likes to decrease performance by using a nib that only has one window. I don't know why they do it, but you can create a window in code with only one line, which compiles and runs much faster.

In your applicationDidFinishLaunching: method:

self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
self.window.rootViewController = [[[MyViewController alloc] initWithNibName:@"MyViewController" bundle:nil] autorelease];
// now you can remove the MainWindow.xib nib.

Personally I prefer to use no nibs at all, but that's one's own choice.

Upvotes: 2

Related Questions