Question

In C# I can write a using statement such as:

using (SqlConnection connection = new SqlConnection("connectionString"))
{
    ...
}

This ensures that the connection object gets disposed once it has gone out of scope. I'm wondering if there is a way to do this within objective-c. I basically have a connection pool that keeps multiple sockets open, rather than needing to open and close a connection every time I use it, I can dip into my connection pool, grab an open connection (or create a new one if required), then release the connection back into the pool once I'm done with it. My objective-c code currently looks something like this:

MyConnection * connection = [ConnectionPool ConnectionWithDetails: @"host/server/port/etc"];
[connection doSomething];
[ConnectionPool ReleaseConnection: connection];

So if for some reason, ReleaseConnection does not get called, the connection is just dangling (it will get freed eventually, but it does not go back into my pool).

Basically, I'm looking for a way that I can eliminate the requirement for calling ReleaseConnection. I've been doing some research, but so far i've come up dry.

Was it helpful?

Solution

Sure, you can use a @try-@catch-@finally block, with the @catch omitted.

MyConnection * connection = [ConnectionPool ConnectionWithDetails: @"host/server/port/etc"];
@try {
    [connection doSomething];
}
@finally {
    [ConnectionPool ReleaseConnection: connection];
}

No matter how you exit the @try block, the @finally block will run.

OTHER TIPS

You could consider using blocks, so instead of creating a connection and using it you would instead submit a block to the connection pool. The pool runs the block at the appropriate time and passes any required parameters (the connection). When the block completes the pool can cleanup as required.

Well if you are making the doSomething method you could work in the call to the [ConnectionPool ReleaseConnection: connection] either into your definition of the doSomething method, or you could provide an optional completion block that makes that call for you

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top