On 17 Mar 2018, at 18:06, amon <[email protected]> wrote:
> 
> Just noticed this while researching... it does not appear to be
> possible to create an NSHost object that is *not* autoreleased.
> Is this true or did I miss something in the docs?

As Fred pointed out earlier, whether you create autoreleased instances doesn’t 
matter.  You can simply write:

NSHost *host;
@autoreleasepool
{
        host = [[NSHost hostWithAddress: someAddress] retain];
}

And now you will have a non-autoreleased instance and all temporary objects 
constructed by the NSHost class will be destroyed (unless otherwise 
referenced).  In ARC mode, you can simply write:

NSHost *host;
@autoreleasepool
{
        host = [[NSHost hostWithAddress: someAddress] retain];
}

If you want to simplify this, then you can wrap it up in a function that takes 
a block:

static inline id get_retained(id(^block)())
{
        @autoreleasepool
        {
                return block();
        }
}

Which you can then use as follows:

NSHost *host = get_retained(^() { return [NSHost currentHost]; });

Or, in Objective-C++ you can do it in a more typesafe way using templates:

#import <Foundation/Foundation.h>

template<typename T>
auto get_retained(T block) -> decltype(block())
{
        @autoreleasepool
        {
                return block();
        }
}

Which you can then use in exactly the same way, or using C++ lambdas (which 
have slightly less horrible syntax):

NSHost *host = get_retained([]{ return [NSHost currentHost]; });

David


_______________________________________________
Discuss-gnustep mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/discuss-gnustep

Reply via email to