Pergunta

I've seen some answers but those didn't expand enough and I think they were before ARC was introduced.

So if I have two NSSstring can I set

string1 =string2;

or

NSString * a1=@"String";
al=@"Lead";

without causing memory leaks or other problems?

Edit: What about view controller or delegate properties set to (copy, nonatomic)?

Edit2: It should be NSString *al=@"String". I hope this doesn't change the idea that it doesn't leak.

Foi útil?

Solução

neither would leak in ARC.

however, you might want to be aware that you are dealing with a reference in this case -- no implicit copy is performed (unless you use a copy or copy-qualified property).

Edit: What about view controller or delegate properties set to (copy, nonatomic)?

for NSStrings? yes, copy should be the default for NSStrings. nonatomic should be the default for everything. of course, there are exceptions to this -- when you might deviate from the defaults.

Outras dicas

No, assigning and re-assigning string literals will not cause a memory leak. You only need to worry about memory leaks when not using ARC and assigning something that uses alloc, retain, copy, mutableCopy or a method prefixed with new.

NSString a1=[@"String" mutableCopy];  
al=@"Lead";//This will cause a leak since you called copy above.

See the Advance Memory Management Rules for details.

Your code is safe and will not leak. Cocoa and NSStrings are quite smart about how they deal with these issues.

You can end up with other interesting things happening because NSStrings are immutable, and you can get weirdness if you try to worry about the pointers themselves. But your examples don't suffer from these issues.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top