Mailing Lists: Apple Mailing Lists
Image of Mac OS face in stamp
Re: Object alloc questions
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Object alloc questions



El 26/02/2004, a las 0:10, T Reaves escribis:

NSString * aString = [@"How does this initialize the object?"];

That should be
NSString* aString = @"How does this initialize the object?";
and is just a short cut. The compiler just takes care of creating the
NSString object. One reason for this is simply as a time save; strings
are used all over the place, and the shortcut makes it easier is all.
The following are functionally equivalent:
NSString* aString = @"aString";
NSString* aString = [NSString stringWithString: @"aString"];
NSString* aString = [[NSString alloc] initWithString: @"aString"];
It's just a mater of convenience; which would you rather type?

Actually, it isn't quite true that they are equivalent, as the following code snippet demonstrates (the actual results are shown as comments):

NSString *test1 = @"Test string";
NSLog(@"test1 retain count is: %d", [test1 retainCount]); // 2147483647
[test1 retain];
NSLog(@"test1 retain count is: %d", [test1 retainCount]); // 2147483647
[test1 release];
NSLog(@"test1 retain count is: %d", [test1 retainCount]); // 2147483647

NSString *test2 = [[NSString alloc] initWithString:@"Test string"];
NSLog(@"test 2 retain count is: %d", [test2 retainCount]); // 1
[test2 retain];
NSLog(@"test 2 retain count is: %d", [test2 retainCount]); // 2
[test2 release];
NSLog(@"test 2 retain count is: %d", [test2 retainCount]); // 1

The first string is a constant string object embedded in the binary at compile time that sticks around for the duration of execution. The second string is dynamically allocated and you have to manage it with release/autorelease like you would with any alloced and inited object. It's not a case of one being a short cut for the other, but of each being a different type of object (although the programmer is shielded from the technicalities thanks the NSString class cluster).

And the usual reminder to the original poster: cocoa-dev is the list to ask this kind of question.

Best wishes,
Greg
_______________________________________________
objc-language mailing list | email@hidden
Help/Unsubscribe/Archives: http://www.lists.apple.com/mailman/listinfo/objc-language
Do not post admin requests to the list. They will be ignored.


References: 
 >Object alloc questions (From: J Tichenor <email@hidden>)
 >Re: Object alloc questions (From: T Reaves <email@hidden>)



Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2011 Apple Inc. All rights reserved.