Obj-c中的typedef结构

gen*_*nie 2 struct typedef objective-c ios

我看到一种奇怪的行为,我需要一些帮助.

在structure.h我有:

typedef struct {
    NSString *summary;
    NSArray *legs;
    NSString *copyrights;
    struct polylineSruct overview_polyline;
    struct directionBounds bounds;    
} route;

typedef struct {
    NSArray *routes;
    NSString *status;
} directions;
Run Code Online (Sandbox Code Playgroud)

在结构中,我有:

(directions) a_Function_that_builds_the_struct
{
    directions direct;

    direct.status = @"OK";

    NSMutableArray *routes = [NSMutableArray array];
    for(xxx)
    {
        route routeL;
        routeL.summary = @"1";
        routeL.copyrights = @"2";

        NSValue *boxedroute = [NSValue valueWithBytes:&routeL objCType:@encode(route)];
        [routes addObject:boxedroute];
    }

    direct.routes = routes;

    return direct;
}
Run Code Online (Sandbox Code Playgroud)

在list_itemsViewController.h我有:

implementation XXX:YYY{
    directions directionsLoc;
}
@property (assign) directions directionsLoc;
Run Code Online (Sandbox Code Playgroud)

在list_itemsViewController.h我有:

@synthesize directionsLoc;
....
- (void)viewDidLoad
{
    ....
    self.directionsLoc = a_Function_that_builds_the_struct;
    ....
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [directionsLoc.routes count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ....
    cell.textLabel.text = directionsLoc.status
    return cell;
}
Run Code Online (Sandbox Code Playgroud)

当我启动应用程序时,我得到了包含所有正确行的列表,如果我为tableView滚动了一点:cellForRowAtIndexPath:属性directionsLoc被取消分配.

有没有人知道我为什么会遇到这个问题?是因为我使用typedef而且保留不被保留?如果我在滚动发生时返回a_Function_that_builds_the_struct和NSArray方向并且执行了tableView:cellForRowAtIndexPath:则数组有一个预期的元素,但对象的状态和路由元素是僵尸.

有没有想过为什么会这样?

谢谢.

Tom*_*mmy 10

结构遵循Objective-C中与C完全相同的规则,因为它是严格的超集.所以直接赋值是浅层副本,解除分配的概念directions directionsLoc;并不真正有意义.

但是,您已经创建了至少一个存储在方向结构中的东西 - routes数组 - 作为自动释放的对象.因此,当下一个当前的自动释放池耗尽时,它将被释放,至少在堆栈展开之前不会发生,如果你自己没有在该区域做任何事情.

所以问题根本不是结构,它是正常的内存管理规则,可能与结构存储值看起来像Objective-C 2.0语法用于设置和获取属性但不涉及任何方法的事实相结合打电话,所以不能保留或复制.

  • 这就是为什么我建议不要在结构中存储对象 - 它只是一个内存管理混乱,几乎没有任何好处.它实际上是*禁止的*除了在即将到来的ARC编译器模式下具有"不安全"类型. (5认同)
  • @genie:将结构转换为真正的Objective-C对象.创建一个"Route"对象和一个"Directions"对象,它们具有相应结构的各个成员的属性. (2认同)