pdi*_*ddy 0 iphone memory-management objective-c
我对内存管理有点失落.我已经读过你应该在你分配的时候发布.但是当你得到一个没有alloc的实例时,你就不应该发布.
这种情况怎么样,只需要知道我是否正确编码.我仍然是iphone dev的新手.
我有一个CustomerRepository类,它有一个方法
- (MSMutableArray *) GetAllCustomers() {
MSMutableArray *customers = [[MSMutableArray alloc] init];
Customer *cust1 = [[Customer alloc] init];
cust1.name = @"John";
Customer *cust2 = [[Customer alloc] init];
cust2.name = @"Tony";
[customers addOjbect:cust1];
[customers addOjbect:cust2];
[cust1 release];
[cust2 release];
return customers;
}
Run Code Online (Sandbox Code Playgroud)
然后我有一个UIViewController
- (void) LoadCustomers() {
CustomerRepository *repo = [[CustomerRepository alloc] init];
MSMutableArray *customers = [repo GetAllCustomers];
// Iterate through all customers and do something
[repo release];
}
Run Code Online (Sandbox Code Playgroud)
所以在这种情况下...... MSMutableArray永远不会被释放?它应该在哪里发布?
如果在需要从函数返回的函数中分配对象,则无法在函数内部释放它.执行此操作的正确方法是自动释放对象.
MSMutableArray *customers = [[MSMutableArray alloc] init]; // ..... do work return [customers autorelease];
这是connivence构造函数所采取的方法
[NSString stringWithString:@"test"];
此方法将返回一个自动释放的字符串,以便您不需要释放它.
如果你不这样做,那么你应该相应的命名你的函数调用者知道它拥有返回的对象,因此需要被释放.这是惯例,而不是一个规则编译器不施加或运行时环境,但以下规则是非常重要的,特别是如果有多人参与了这个项目.
| 归档时间: |
|
| 查看次数: |
118 次 |
| 最近记录: |