NSString literal vs alloc

You can create a NSString with literal syntax or allocation.

Literal:

NSString *str = @”hasancan”;

Alloc:

NSString *str = [[NSString alloc] initWithString:@”hasancan”];

Literal version will be stored in an area called data segment and this area never changes when application is launched. So it is treated like a constant.

However if you alloc NSString, it is created on the heap and you have to manage its memory.

Literal version is suggested because it reduces source code size, much easier to read and no need to manage memory.

Leave a comment