2

first post here. I was reading through an Objective-C tutorial earlier, and I saw that they had made a couple of NSString instance variables like this:

@implementation MyViewController {
NSString *stringOne;
NSString *stringTwo;
NSString *stringThree;
NSString *stringFour;
NSString *stringFive;
}

And then simply used them in ViewDidLoad like this:

- (void)viewDidLoad
{
[super viewDidLoad];

stringOne = @"Hello.";
stringTwo = @"Goodbye.";
stringThree = @"Can't think of anything else to say.";
stringFour = @"Help...";
stringFive = @"Pheww, done.";
}

How have they done this without instantiating the string? Why does this work? Surely you'd have to do something like stringOne = [NSString stringFromString:@"Hello."]; to properly alloc and init the object before you could simply do stringOne= @"Hello.";.

Sorry if this a dumb question, but I find these little things throw me.

Thanks, Mike

Mike1690
  • 33
  • 5
  • 2
    They are instantiating them via an assignment to a string literal. – Carl Veazey Mar 31 '13 at 17:40
  • 3
    Never use `stringWithFormat` unless you actually have a string that you need to format. – rmaddy Mar 31 '13 at 17:41
  • It took me too long to get supporting link on mobile to edit last comment. Compiler actually allocates those strings see http://stackoverflow.com/questions/8032375/difference-between-nsstring-literals – Carl Veazey Mar 31 '13 at 17:46
  • 2
    Also, people who do stuff like `NSObject *object = [[NSObject alloc] init]; object = somethingElse;` are doing it wrong so don't follow their example :) – Carl Veazey Mar 31 '13 at 17:50
  • Thank you guys. I had no idea that I didn't have instantiate NSString when using `@"..."`. – Mike1690 Mar 31 '13 at 17:52
  • 1
    Thanks Carl. So instead of that it should be `NSObject *object = somethingElse`, as that `somethingElse` is already instanced, `object` doesn't need to be, right? – Mike1690 Mar 31 '13 at 17:56
  • Relevant: http://stackoverflow.com/q/8032375/581994 – Hot Licks Apr 01 '13 at 15:01

4 Answers4

6

From the Apple String Programming Guide:

Creating Strings

The simplest way to create a string object in source code is to use the Objective-C @"..." construct:

NSString *temp = @"Contrafibularity";

Note that, when creating a string constant in this fashion, you should use UTF-8 characters. Such an object is created at compile time and exists throughout your program’s execution. The compiler makes such object constants unique on a per-module basis, and they’re never deallocated. You can also send messages directly to a string constant as you do any other string:

BOOL same = [@"comparison" isEqualToString:myString];
Community
  • 1
  • 1
tkanzakic
  • 5,499
  • 16
  • 34
  • 41
  • Thanks for the answer, it's nice and concise. That bit at the bottom is very useful; it's going to be strange thinking of `@"..."` as something that can receive messages. – Mike1690 Mar 31 '13 at 18:07
  • the @ in objective-c is an object operator, everything starting with it is an object, for example `@11` is a `NSNumber` that *store* the value 11, not an `int`. On the other hands, if you think this is the right answer to your question please accept it – tkanzakic Mar 31 '13 at 18:27
3

String constants like @"Hello" are already allocated and initialized for you by the compiler.

progrmr
  • 75,956
  • 16
  • 112
  • 147
  • Thanks for the answer. So if `@"..."` is allocated and initialised, I never have to instantiate NSString, correct? – Mike1690 Mar 31 '13 at 17:52
  • Right, it is a preallocated `NSString*` object (technically a `const NSString* const`). You can use a string literal (such as `@"...:"`) anywhere that takes an `NSString*` object. (Except of course that it's a constant and can't be modified) – progrmr Mar 31 '13 at 17:59
  • Perfect, thank you very much :) All clear. I've been instantiating NSString unnecessarily far too often in my code... Seems like a massive clean up is in order. – Mike1690 Mar 31 '13 at 18:02
2

actually this can be said "syntactic sugar". there are some other type of NS object that can be creatable without allocation or formatting. e.g:

NSNumber *intNumber1 = @42;
NSNumber *intNumber2 = [NSNumber numberWithInt:42];

NSNumber *doubleNumber1 = @3.1415926;
NSNumber *doubleNumber2 = [NSNumber numberWithDouble:3.1415926];

NSNumber *charNumber1 = @'A';
NSNumber *charNumber2 = [NSNumber numberWithChar:'A'];

NSNumber *boolNumber1 = @YES;
NSNumber *boolNumber2 = [NSNumber numberWithBool:YES];

NSNumber *unsignedIntNumber1 = @256u;
NSNumber *unsignedIntNumber2 = [NSNumber numberWithUnsignedInt:256u];

NSNumber *floatNumber1 = @2.718f;
NSNumber *floatNumber2 = [NSNumber numberWithFloat:2.718f];

// an array with string and number literals
NSArray *array1 = @[@"foo", @42, @"bar", @3.14];

// and the old way
NSArray *array2 = [NSArray arrayWithObjects:@"foo", 
                                            [NSNumber numberWithInt:42], 
                                            @"bar", 
                                            [NSNumber numberWithDouble:3.14], 
                                            nil];

// a dictionary literal
NSDictionary *dictionary1 = @{ @1: @"red", @2: @"green", @3: @"blue" };

// old style
NSDictionary *dictionary2 = [NSDictionary dictionaryWithObjectsAndKeys:@"red", @1, 
                                                                       @"green", @2, 
                                                                       @"blue", @3, 
                                                                       nil];

for more information, see "Something wonderful: new Objective-C literal syntax".

Jeromy French
  • 11,812
  • 19
  • 76
  • 129
meth
  • 1,887
  • 2
  • 18
  • 33
  • Where does this answer address the question about `NSString`? – rmaddy Mar 31 '13 at 18:26
  • You Sir, have blown my mind. I've added this to my little book of syntax as it's comprehensive and helps me to realise when to alloc/init and when to not. Thanks. By the way, sorry I can't +1 as I don't have enough rep apparently. – Mike1690 Mar 31 '13 at 18:27
  • @rmaddy i explained that this is just a syntax issue and give other examples. did you read my answer? – meth Mar 31 '13 at 18:28
  • @rmaddy I think he realised that I had understood the NSString problem and was providing further examples to help me understand the concept. – Mike1690 Mar 31 '13 at 18:28
  • 1
    I get all of that. I'm just pointing out that this answer doesn't answer the question. It only provides unrelated, but useful, information. – rmaddy Mar 31 '13 at 18:33
2

Just remember this basic thing:-

NSString *string = ...

This is a pointer to an object, "not an object"!

Therefore, the statement: NSString *string = @"Hello"; assigns the address of @"Hello" object to the pointer string.

@"Hello" is interpreted as a constant string by the compiler and the compiler itself allocates the memory for it.

Similarly, the statement

NSObject *myObject = somethingElse;

assigns the address of somethingElse to pointer myObject, and that somethingElse should already be allocated and initialised.

Therefore, the statement: NSObject *myObject = [[NSObject alloc] init]; allocates and initializes a NSObject object at a particular memory location and assigns its address to myObject.

Hence, myObject contains address of an object in memory, for ex: 0x4324234.

Just see that we are not writing "Hello" but @"Hello", this @ symbol before the string literal tells the compiler that this is an object and it returns the address.

I hope this would answer your question and clear your doubts. :)

Burhanuddin Sunelwala
  • 5,318
  • 3
  • 25
  • 51