Forum Archive

ObjC generics support?

zrzka

Hi,

I tried to help with this question, wrote some code which should display yellow button, but the Pythonista is crashing.

The problem is in the return value of tableView_editActionsForRowAtIndexPath_ where the type should be NSArray<UITableViewRowAction *>. Is there a way how to instantiate NS[Mutable]Array with generics?

I assume that it's crashing because of wrong type as it is just NSArray? Is my assumption correct?

Thx,
Zrzka

#!python3

import ui
from objc_util import *

#
# UITableViewDelegate
#

def handler(_cmd, action, index_path):
    print('Trash it tapped')


def tableView_editActionsForRowAtIndexPath_(self, cmd, table_view, index_path):
    yellow = ObjCClass('UIColor').yellowColor()

    block_handler = ObjCBlock(handler, restype=None, argtypes=[c_void_p, c_void_p, c_void_p])

    action = ObjCClass('UITableViewRowAction').rowActionWithStyle_title_handler_(0, ns('Trash it!'), block_handler)
    action.setBackgroundColor(yellow)

#   return ns([])  <- crash
# return ns([action]) <- crash
    return None # ok


def make_table_view_delegate():
    methods = [tableView_editActionsForRowAtIndexPath_]
    protocols = ['UITableViewDelegate']
    delegate = create_objc_class('CustomTableViewDelegate', methods=methods, protocols=protocols)
    return delegate.alloc().init()

#
# UITableView
#

table_view = ui.TableView(name='Custom Action', frame=(0, 0, 300, 480))
table_view.data_source = ui.ListDataSource(['Hallo', 'Hi', 'Ciao'])

table_view_objc = ObjCInstance(table_view)
table_view_objc.setDelegate(make_table_view_delegate())

table_view.present('sheet')
JonB

@zrzka said:

I suspect the problem is because you are not storing a reference to block_handler, and it is getting deleted when it falls out of scope? Try defining that outside of the callback.

omz

You need to return the array as a pointer:

return ns([action]).ptr
zrzka

Ahhh, thanks! Both comments helped, thx guys, works perfectly now.