vitaliy-zh
vitaliy-zh

Reputation: 205

Delphi: ARC and Objective-C wrapped objects - how to release?

In Delphi/FMX there is no ARC for the Objective-C objects represented by the import wrapper classes and interfaces.

When dealing with Objective-C objects you’ll have to call retain and release yourself at the correct points. Allocating a new Objective-C object will initialize its reference count to 1 and calling release will drop it to 0 thus destroying it. http://ridingdelphi.blogspot.de/2014/01/the-quest-to-migrate-ios-squarecam-app_3169.html

For example, i want to create a UILabel dynamically. According to the reference above, my code should be look like this (I'm assuming that I have chosen the positions for retail and release correctly):

    procedure TForm1.Button1Click(Sender: TObject);
    var
      lbl: UILabel;
    begin
      lbl := TUILabel.Wrap(TUILabel.alloc.init);
      lbl.retain;
      ...
      lbl.release;
    end;

It does not work. What is the right way to release wrapped Objective-C objects in Delphi/FMX?

With "It doesn't works" I mean that the UILabel is not released as expected ans still allocates the memory. I found this with the help of the Xcode Allocation Instrument.

Upvotes: 1

Views: 157

Answers (1)

Sebastian Z
Sebastian Z

Reputation: 4740

TUILabel.alloc.init increases the reference count by one. After your call to retain you have a reference count of two. But then you release the object only once.

So you either have to call release twice:

procedure TForm1.Button1Click(Sender: TObject);
var
  lbl: UILabel;
begin
  lbl := TUILabel.Wrap(TUILabel.alloc.init);
  lbl.retain;
  ...
  lbl.release;
  lbl.release;
end;

Or remove the call to retain:

procedure TForm1.Button1Click(Sender: TObject);
var
  lbl: UILabel;
begin
  lbl := TUILabel.Wrap(TUILabel.alloc.init);
  ...
  lbl.release;
end;

Upvotes: 2

Related Questions