开发者

Can a struct become deallocated?

I've declared a struct in my header file like this:

typedef struct {
NSString *department;
NSString *departmentId;
}  Department;

Department currentDepartment;

This struct is in a fairly simple class. I assign the struct values in viewDidLoad. Jus开发者_JS百科t before leaving viewDidLoad, I see the struct values are still there. After the user clicks a segment control, I reassign the struct values. Before assigning values, I see the two struct values are 0x0. I do have NSZombieEnabled, which is printing out this when I mouse over the struct while the app is running and one of my breakpoints have been hit:

MyApp[25722:207] *** -[CFString _cfTypeID]: message sent to deallocated instance 0xfc0e90

I'm not creating an instance of the struct or deallocating it. How can it be getting deallocated?


I strongly advise against putting objects in structs if at all possible. Structs are just dumb collections of data and cannot manage their members' memory like objects can with accessors. This means client code will have to take on the responsibilty of retaining and releasing the structs members whenever it deals with them and making sure they are released before the strict goes out of scope — it's not really that easy. You'd be better off creating a lightweight object.


No, structs can be freed, but not unless you do that yourself somewhere in your code. What's being deallocated in this case is a string, as can be seen from the error message. Check the objects you're using when you set the department and departmentId members.

In fact, you need to be extra careful about memory management in general when you assign objects to struct members. In this case, you may need to send a -retain message to the strings, or change the way you're creating them so that you use alloc/init... or copy rather than stringWith... or other methods.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜