Using C Structs which contains ObjC Objects?

Anything you retain you must release. However, there is nothing that says you must retain them. If the structure is "owning" the objects, then yes, you should retain them, and then you must release them. If the objects are retained elsewhere, though, you might want to consider weak references where you don't retain the objects.


In general you would be much better off creating a simple container class. That way all the memory management is easy and you are able to use the object in the standard Cocoa container classes without mucking around wrapping the struct in an NSValue or whatever.

The only time it might be acceptable to use a struct in this way is if you have extremely performance-critical code where the object overhead might become a problem.

@interface ISKNewsCategory : NSObject
{
    NSString *name;
    NSString *code;
}
@property (copy) NSString *name;
@property (copy) NSString *code;
@end

@implementation ISKNewsCategory
@synthesize name,code;
- (void)dealloc
{
    self.name = nil;
    self.code = nil;
    [super dealloc];
}
@end

As of 2018 you can now use ObjC pointers in C structs and they are retained while the struct is in memory. https://devstreaming-cdn.apple.com/videos/wwdc/2018/409t8zw7rumablsh/409/409_whats_new_in_llvm.pdf

Tags:

Objective C