Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using C Structs which contains ObjC Objects?

Tags:

objective-c

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;
}
like image 673
GuidoMB Avatar asked Mar 21 '10 21:03

GuidoMB


People also ask

Can structs have functions Objective-C?

Structs are a C construct. The compiler is telling you, in very unambiguous terms, that you can't have Objective-C objects inside a struct, not that structs are illegal.

How do you initialize a struct in Objective-C?

Initializing Structures The fastest way to initialize a structure is to enclose the values in a pair of braces: Date today = {5, 22, 2011}; You can list fewer values, and they will be filled in until the end of the values you list. The remaining values will be undefined.


2 Answers

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
like image 129
Rob Keniger Avatar answered Nov 07 '22 06:11

Rob Keniger


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

like image 21
Gabe Avatar answered Nov 07 '22 06:11

Gabe