tags:

views:

68

answers:

3

I'm using C structs in objc and I've created a function that assembles the structure like the one from the Cocoa API. The things is that this structure is not like NSRect o NSPoint this structure packs objc objects soo I'm seeing a potential memory leak here. Do I need to provide a function to 'release' the structure?

I'am not creating a ISKNewsCategory class because there will be no behavior but Do you think this is a good approach or I should define the class even doe there will be no behavior?

typedef struct ISK_NewsCategory {
    NSString *name;
    NSString *code
} ISKNewsCategory;

NS_INLINE ISKNewsCategory ISKMakeNewsCategory(NSString *name, NSString *code) {
    ISKNewsCategory category;
    category.name = [name retain];
    category.code = [code retain];
    return category;
}
+2  A: 

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.

chpwn
A: 

I hate to create classes with no behavior too. :/ This is a sad aspect of Objective-C: classes are verbose.

You have to remember that structures in C are copied each time they're passed around. Therefore, if your structures retain their objects and you give them to someone else, you automatically end up with an erroneous reference count for the objects in it.

If you plan on passing around your objects at all, I think you should make it a full-fledged class. If you don't, a simple struct will be okay.

As of the need of a "destructor", you should have one. You should always have one if there is cleanup to do for your structure.

zneak
actually, the copying will not cause any extra retains any more than passing an object directly, since only the pointer is copied.
cobbal
@cobbal: this is what I meant. If you pass your structure around, the pointers to the objects will be copied, and if you meant to retain them for each structure in which they live, you can't just do that.
zneak
+3  A: 

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
Rob Keniger