简体   繁体   中英

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM