views:

35

answers:

1

Hi,

wonder whether someone can help me with the following one...

I have a struct

typedef struct {
    NSString *section;
    NSString *row;
} myStructDef;

that I fill and write from function parameters "value[x]" to an NSMutableArray iVar "Arr1" of NSMUtableArrays local "Arr2" using:

myStruct.section = [NSString stringWithUTF8String:(char *)values[0]];
for (int i=1; i < count; i++) {
    myStruct.row = [NSString stringWithUTF8String:(char *)values[i]];
    [Arr2 addObject:[NSValue valueWithBytes:&myStruct objCType:@encode(myStructDef)]];
    [Arr1 addObject:Arr2];
}

Writing the array seems to work fine (the debugger shows the array building and I can retrieve the NSValue correctly using

[[Arr2 objectAtIndex:i-1] getValue:&myStruct];

added to the for-loop above.

THE PROBLEM comes when retrieving the array values in a subsequent function using:

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    myStructDef myStruct;
    [[[Arr1 objectAtIndex:section] objectAtIndex:0] getValue:&myStruct];
    return myStruct.section;
}

Whilst step1 "[Arr1 objectAtIndex:section]" is retrieved correctly, step3 "... getValue:&myStruct]" seems to fail. I also tried stripping the 3 actions into separate steps, that is when I can see that an Object is returned in step2. The getValue: fails.

Any clue what i am doing wrong?

cheers iFloh :)

+2  A: 

[NSString stringWithUTF8String:] returns a string that you don't own. You aren't explicitly retaining it, and a C struct won't implicitly retain it, either. So you stick your NSString pointers into your array, but the strings they point to are almost certainly deallocated by the time you're trying to pull them back out.

Sixten Otto
super fast and spot-on, THANK YOU :)
iFloh
Hi Otto,this one made me think again. when I retain my strings, how can I best release them again?regards iFloh
iFloh
Without knowing much about how your app is put together, it's a little hard to say. But, worst-case, wherever it is that you're releasing `Arr1`, you might have to walk through it, releasing all of the strings it contains. (Another approach would be to replace the C structs you're using with actual objects, so that they can manage themselves.)
Sixten Otto
I moved my structs to Objects and can see the advantages of this approach. e.g. handling the structs, the ability to keep the methods with the struct and from above ... emory mgmt. Thanks
iFloh