Are Objective-C's (id) methods used for initializing after alloc
only?
NSString *stringC = @"My World";
NSString *sample = [[NSString alloc] initWithString:stringC];
Are Objective-C's (id) methods used for initializing after alloc
only?
NSString *stringC = @"My World";
NSString *sample = [[NSString alloc] initWithString:stringC];
Objective-C's init methods are intended for only newly-alloc'd instances, and here's why:
init methods are allowed to re-assign self
and return a different pointer than what the associated alloc
did (which is why you always assign your variable as the return of init). This means that calling init on a previously-initialized object may give you back a pointer to new memory, which creates a few problems.
First, if you don't assign the new pointer to your variable, it was pointless or worse. Second, any additional pointers to the "old" object are now "dangling", which will get nasty.
In terms of the @"foo"
construct, it's roughly analogous to a const string in C (NSStrings are immutable, btw), but it will be a pointer to an NSString instance instead of a pointer to an in-volatile char, and you don't need to init
it. I'm not sure if you left out the asterisk by mistake or not, but @"" does produce a pointer to an NSString, so that line needs the asterisk, just like the next.
id is Objective-C's special void *
for objects It essentially tells the compiler two things:
and #2 there has one quintessential implication: you can send messages to it
So similar to void *, you can get away with passing something type-cast as (id) where some other object-type is required and the compiler won't complain.
It's better to say that prior to the init* methods, you should alloc.
For example,
NSString * test = [NSString stringWithFormat:@"hello world"];
also returns an ID but is not after an "alloc" call.