objective-c struct properties are released before usage -
i have struct in objective-c code >
typedef struct { __unsafe_unretained nsstring *string1; __unsafe_unretained nsstring *string2; __unsafe_unretained nsstring *string3; __unsafe_unretained nsstring *string4; __unsafe_unretained nsstring *string5; . . . __unsafe_unretained nsstring *string10; } mystruct;
in model class store these structs in array declared
@property (nonatomic, strong) nsmutablearray *mystructarray;
i construct in .m file during runtime
nsmutablearray *mytemparray = [nsmutablearray array]; (nsdictionary *jsondict in jsonarray) { mystruct stringsstruct = parsewithdictionary(jsondict); [mytemparray addobject:[nsvalue value:&stringsstruct withobjctype:@encode(mystruct)]]; } myobject.mystructarray = mytemparray;
the problem when try access after parsing / constructing inside objects deallocated & received error
-[cfurl length]: message sent deallocated instance
here how access properties later way,
mystruct mystruct; [[myobject.mystructarray objectatindex:someindex] getvalue:&mystruct]; nslog(@"%@",mystruct.string1); // << bam! crash
how fix ? there way make sure objects objects remain intact without deallocing until i'm done ? i'm using arc & cannot remove __unsafe_unretained hence.
you explicitly told arc out of way using __unsafe_unretained
, it's way struct hold object values. doesn't come without price: pay memory management fee.
you manually have retain/release object place in structs using cfrelease
/cfretain
, very error prone.
let me stress point: __unsafe_unretained. name hasn't been picked randomly.
my advice is: stop using structs , turn them objects.
@interface myclass : nsobject @property (nonatomic, copy) nsstring *string1; @property (nonatomic, copy) nsstring *string2; ... @property (nonatomic, copy) nsstring *string10; @end
it's better under many point of views:
- you memory management "for free" arc
- you can define convenience methods in class
- it's more idiomatic objective-c wise
Comments
Post a Comment