I'm seeing a weird behavior and I would need some help with it.
In structure.h I have:
typedef struct {
NSString *summary;
NSArray *legs;
NSString *copyrights;
struct polylineSruct overview_polyline;
struct directionBounds bounds;
} route开发者_开发问答;
typedef struct {
NSArray *routes;
NSString *status;
} directions;
In structure.m I have:
(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;
}
in list_itemsViewController.h I have:
implementation XXX:YYY{
directions directionsLoc;
}
@property (assign) directions directionsLoc;
in list_itemsViewController.h I have:
@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;
}
When I start the application I get the list with all the correct rows, if I scroll a little bit for the tableView:cellForRowAtIndexPath: the property directionsLoc is deallocated.
Does anybody have any idea why I get this problem? Is it because I use typedef and the retention is not kept? If I return in the a_Function_that_builds_the_struct and NSArray of directions when the scrolling happens and tableView:cellForRowAtIndexPath: is executed the array had one element as expected but the status and routes elements of the object are zombies.
Any thought on why this happens?
Thank you.
Structs follow exactly the same rules in Objective-C as C, as it's a strict superset. So a direct assignment is a shallow copy, and the concept of deallocating just directions directionsLoc;
doesn't really make sense.
However, you've created at least one of the things that is stored within the directions struct — the routes
array — as an autoreleased object. Therefore it will be released when next the current autorelease pool is drained, which won't happen at least until the stack unwinds if you're not doing anything in that area yourself.
So the problem isn't the struct at all, it's the normal memory management rules, possibly combined with the fact that storing values to a struct looks like Objective-C 2.0 syntax for setting and getting properties but doesn't involve any sort of method call, so can't in itself retain or copy.
精彩评论