3
votes

While playing around with ARC, I noticed that when I have a weak String:

@property (weak, nonatomic) NSString *myString;

And then if I were to do this:

self.myString = [[NSString alloc] init];

or even

[[NSString alloc] initWithString:@""]

Xcode immediately warns me "Assigning retained object to weak property; object will be released after assignment". And while I can understand that, because its reference count is 0, why does this work with no warnings:

self.myString = @"";

What difference does it make for ARC?

2
If the answer I gave clarifies your understanding, do not hesitate to validate it. - Zaphod

2 Answers

4
votes

Because when you have a weak property, ARC does not increase the reference count...

So when you write:

self.myString = [[NSString alloc] init];

ARC adds a release just after, because it is the same as writing:

[[NSString alloc] init];

The main difference with @"" it is that it's a static string, in a way retained somewhere else...

Each time you use @"" it points to the same object.

Edit: The difference between @"" and [[NSString alloc] initWithString:@""] is that the first is a static string and is processed at compile time. If it is used elsewhere the other use will point to the same static string. The second, is processed at runtime. It really creates a new object, with its retain count and so on... That's why ARC does its job for the created instance (you specifically call a alloc) and why it does not care for static strings.

0
votes

For ' Ok, so why does it show the same warning if I do this: [[NSString alloc] initWithString:@""] ? '

When you use [[NSString alloc] initWithString:@""], system will create a new string with @"" and it will be allocated in memory heap.