ios alloc-release

时间:2012-02-05 19:04:22

标签: ios release alloc

我的应用程序正在接收内存警告,因为它要求大量内存。我尝试释放每个分配。但是,有时我不知道该怎么做。

例如:我有两对.h和.m文件。其中一个与服务器建立连接,另一个与本地SQLite建立连接。

通常,从这些文件调用方法的代码如下:

-(NSMutableArray *) getRecentActivity{
    LocalStorageController *local = [[LocalStorageController alloc]init];
    return [local getRecentActivity];
}

getRecentActivity返回NSMutableArray。

好吧,在那段代码中,我们可以看到我正在为LocalStorageController分配内存,但我从不调用release方法,所以,我想,我调用的函数越多,我将分配的内存越多。 / p>

如果我在init之后调用autorelease,它将崩溃。

此外,通常,我使用其他类型的代码:

    ServerConnection *serv = [[ServerConnection alloc]init];
    NSMutableArray list = [serv getMyListOfContacts];

使用ASIHTTPRequest,如果我在第二行之后调用[serv release];,则应用程序崩溃,EXC_BAD_ACCESS指向ASIHTTPRequest库中的一行。

如何管理这种情况?

非常感谢!

2 个答案:

答案 0 :(得分:2)

第一种情况很简单;

-(NSMutableArray *) getRecentActivity{
    LocalStorageController *local = [[LocalStorageController alloc]init];
    NSMutableArray *tmp = [local getRecentActivity];
    [local release];
    return tmp;
}

第二种情况很难在没有看到更多实际代码的情况下以一般方式解决。

答案 1 :(得分:0)

使用serv作为属性将修复此保留/释放问题。

在你的.h:

@property (nonatomic, retain) ServerConnection *server;

在你的.m:

@synthesize server;

- (void)dealloc {
    [server release];
    // The rest of your releases here...
    [super dealloc];
}

- (void)yourMethod {
    ServerConnection *myServConnection = [[ServerConnection alloc] init];
    self.serv = myServConnection;
    [myServConnection release];
    NSMutableArray list = [self.serv getMyListOfContacts];
}

从那时起,继续在此类中继续使用self.serv,对于释放对象不会有任何问题。

相关问题