Delphi + iOS: How to declare simple ObjC-Class?

雨燕双飞 提交于 2020-01-10 20:03:34

问题


How I can declare a simple ObjC-Class in Delphi/Firemonkey (XE5 or XE6)? I want to create an animation delegate class with some delegate methods inside of this class.

Thanks!


回答1:


Create an interface with your methods and derive from IObjectiveC. Also create a guid. I'm not posting one here, so that nobody is tempted to use mine.

  ISampleDelegate = interface(IObjectiveC)
    ['{put-your-own-guid-here}'] // <-- Press Ctrl+Shift+G to create your own guid - must be unique for every interface
    procedure DispatchItem(Sender: Pointer); cdecl;
  end;

Create your delegate implementation and derive from TOCLocal. It should implement your delegate interface.

  TSampleDelegate = class(TOCLocal, ISampleDelegate)
  private
    FOwner: TMenuItem;
  public
    constructor Create(AOwner: TMenuItem);
    procedure DispatchItem(Sender: Pointer); cdecl;
  end;

constructor TSampleDelegate.Create(AOwner: TMenuItem);
begin
  inherited Create;
  FOwner := AOwner;
end;

Create the delegate:

FDelegate: ISampleDelegate;

FDelegate := TSampleDelegate.Create(Self);

Assign your delegate:

Item.setDelegate(FDelegate);

Free your delegate:

Item.setDelegate(nil);
TNSObject.Wrap((FDelegate as ILocalObject).GetObjectID).release; // don't forget this one! The create constructor calls Alloc in inherited
FDelegate := nil;



回答2:


I would like to add to Sebastian Z's answer (but I'm not allowed to comment yet) and just say that the methods in the class that are implementing the delegate interface should be declared as public (as Sebastian has done). Either that or make sure the appropriate RTTI information is exposed for the methods, otherwise an EObjectiveC exception is raised with the message "Method ... not found" when the object is created.

Edit: I'm fairly sure that Item.setDelegate(FDelegate); in Sebastian Z's answer is wrong and that GetObjectID must be used to get the pointer to the delegate object. I was getting Access violations until I made that change.



来源:https://stackoverflow.com/questions/24682261/delphi-ios-how-to-declare-simple-objc-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!