-1

I am confused in this can you tell me which one is better and why?

I read somewhere that this both are used for allocing and initializing. somebody was telling me that you cant do like newWithString and all other things like that but when I tried in Xcode then Its not giving me error

      NSString *AddEmail  =[[NSString alloc]initWithString:@"Add Email"];

      NSString *AddEmail  =[NSString new];

do both will work In same way?

thank you in advance

Prakash Desai
  • 511
  • 3
  • 14

2 Answers2

3

[[SomeClass alloc] init] will give the same result as [SomeClass new]. new is implemented as

+ (id) new
{
    return [[self alloc] init];
}

The newWithString method you use gives a quite explicit warning : "Class method +newWithString not found", so even if you code compile, it will fail on this line. (Unless you declared a category on NSString).

I tend to prefer [[alloc] init], because you can allocate an object then choose how you will initialize its variables, according to the init method you chose..

Regexident
  • 29,441
  • 10
  • 93
  • 100
Michaël Azevedo
  • 3,874
  • 7
  • 31
  • 45
1

+[NSString new] simply returns an empty, immutable string.

It is equivalent to [[NSString alloc] init].

Your examples are not the same. If I were to correctly guess your intention, NSString * AddEmail = @"Add Email"; would be all you would need to write. You do not need to use +alloc, -initWithString:, +stringWithString:, etc. in this example because @"Add Email" is already an NSString.

[[TYPE alloc] init] and [TYPE new] are equivalent (unless overridden). Which you choose is your preference. I prefer [TYPE new] because it is shorter and there is no need to separate (or pronounce) the alloc/init message chain whenever you create a 'new' object.

justin
  • 104,054
  • 14
  • 179
  • 226