0

I have a struct in my Objective-C code like this >

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 my model class I store these structs in an array declared

@property (nonatomic, strong) NSMutableArray *myStructArray;

I construct this in my .m file during runtime like this

NSMutableArray *myTempArray = [NSMutableArray array];
for (NSDictionary *jsonDict in jsonArray)
{
 MyStruct stringsStruct = parseWithDictionary(jsonDict);
 [myTempArray addObject:[NSValue value:&stringsStruct withObjCType:@encode(MyStruct)]];
}
myObject.myStructArray = myTempArray;

The problem is when I try to access this after parsing / constructing the inside objects are already deallocated & I received the error

-[CFURL length]: message sent to deallocated instance 

Here is how I access the properties later by the way,

 MyStruct myStruct; 
[[myObject.myStructArray objectAtIndex:someIndex] getValue:&myStruct];
NSLog(@"%@",myStruct.string1); // << bam! crash

How do I fix this ? Is there a way to make sure the objects objects remain intact without deallocing until i'm done with it ? I'm using ARC & cannot remove with __unsafe_unretained hence.

4

1 回答 1

2

您明确告诉 ARC 通过使用让开,__unsafe_unretained这是获取 struct 保存对象值的唯一方法。这并非没有代价:您支付内存管理费。

您必须使用 / 手动保留/释放放置在结构中的任何对象CFReleaseCFRetain容易出错。

让我强调一点:__ UNSAFE _unretained。这个名字不是随便取的。

我的建议是:停止使用结构并将它们变成对象。

@interface MyClass : NSObject

@property (nonatomic, copy) NSString *string1;
@property (nonatomic, copy) NSString *string2;
...
@property (nonatomic, copy) NSString *string10;

@end

在许多观点下它更好:

  • 您可以使用 ARC“免费”获得内存管理
  • 您可以在类中定义便捷方法
  • 它更符合 Objective-C 的习惯
于 2013-08-28T17:09:18.193 回答