2009-10-03 94 views
1

当前我正在使用NSMutableArray作为属性。不过,我也使用opengl和出于性能的目的,我想用malloc来创建一个指向int数组的指针并将其作为属性。malloc属性目标c

我该如何做到这一点在目标c,仍然确保我的记忆是安全的?也许这在目标c中不是一件安全的事情?将malloc与属性混合。

回答

4

您可以将指针指定为属性。你将不得不自己管理内存(也就是说,因为它不是一个客观的C对象,它不能被自动保留和释放)。

以下内容应该可以工作。

@interface ClassWithProperties : NSObject { 
    int *pointer; 
} 

@property int *pointer; 

@end 


@implementation ClassWithProperties 

@synthesize pointer; 

- (void) initializePointer { 
    self.pointer = malloc(sizeof(int) * 8); 
} 

- (void) dealloc { 
    free(self.pointer); 
} 

@end 
+1

我推荐一个'(非原子)'(删除线程的开销)'@ property'和'如果之后(self.pointer!= NULL)在''的自由(self.pointer)前'。 – MrMage 2009-10-03 15:07:53

+1

在free()之前你不需要'if(self.pointer!= NULL)'检查,如果传递给它的指针是NULL,那么C标准要求'free()'不起作用。 – 2009-10-03 15:14:47