objective c - ARC and "copy" method -


i'm using sbjson parse json strings.

like this:

nsdictionary *dict = received_notification.object; 

should use

nsstring *name  = [[dict valueforkey:@"name"] copy]; 

or

nsstring *name  = [dict valueforkey:@"name"]; 

i think first method copies nsstring , after dict can released.

but second expression "name" keeps reference dict , can't released.

am wrong?

you right in first case, , copying can useful because nsstring has mutable subclass (nsmutablestring), copy ensures have real nsstring in *name , not it's mutable subclass.
(more: talking nsstring, copy used on properties, depending on how structured code can useful on local variable)

but in second case wrong. first thing: using arc (not mentioned in post see tag), local variables __strong default

when do:

nsstring *name = [dict objectforkey:@"name"]; // use objectforkey since valueforkey kvc, suggested martin r 

you not taking reference dictionary, taking reference object @ key "name" inside dictionary (that should nsstring). so, arc sends retain message automatically nsstring. @ moment, string referenced at least 2 things:
- *name pointer
- nsdictionary

if dictionary deallocated, nsstring instance has reference (from *name) , not released until last reference removed.

last thing: since in example there local variables, strong references created here lost after method ends (since local variables destroyed). referenced objects deallocated if have no other strong references in other parts of code.


Comments

Popular posts from this blog

PySide and Qt Properties: Connecting signals from Python to QML -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

scala - 'wrong top statement declaration' when using slick in IntelliJ -