On 2018-02-05 16:49, mrphobby wrote:

I've been playing around with this a bit and it works pretty well. One thing that bothers me is the handling of NSString. I came up with the following class to handle strings and make sure they do not leak. But maybe there is a nicer way to handle this in D?

Note that this applies to all classes, not just NSString.

class NSStringRef {
public:
     this(string s) {
         str_ = NSString.alloc.initWithBytes(cast(immutable(ubyte)*) s.ptr,
                                             s.length,
NSStringEncoding.NSUTF8StringEncoding);
     }

     ~this() {
         str_.release();
     }

Note that this is not deterministic. There's not even a guarantee that a destructor for a class will be run at all.

     NSString str() @property {
         return str_;
     }

private:
     NSString str_;
}

And then you have to use it like this:

     NSStringRef s = new NSStringRef("Hello");
     NSLog(s.str);

You can add an "alias this" [1] to avoid calling "str" explicitly.

Ideally I would like to write code more like this (without leaking the NSString):

     NSLog("Hello".nsstring);

Surely this must be possible in D somehow? :)

Currently the only correct way would be to wrap the class in a struct. There as been some talk to extend the language to support for reference counted classes [2].

[1] https://dlang.org/spec/class.html#alias-this
[2] https://wiki.dlang.org/DIP74

--
/Jacob Carlborg

Reply via email to