Попытайтесь использовать метод тестирования Java 8 предиката
, Вот полный пример его.
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
public class Test {
public static final List VALUES = Arrays.asList("AA", "AB", "BC", "CD", "AE");
public static void main(String args[]) {
Predicate containsLetterA = VALUES -> VALUES.contains("AB");
for (String i : VALUES) {
System.out.println(containsLetterA.test(i));
}
}
}
http://mytechnologythought.blogspot.com/2019/10/java-8-predicate-test-method-example.html
Roll your own:
// In some .h file. #import to make the extension methods 'visible' to your code.
@interface NSThread (FunctionExtension)
+(void)detachNewThreadByCallingFunction:(void (*)(void *))function data:(void *)data;
-(id)initWithFunction:(void (*)(void *))function data:(void *)data;
@end
// In some .m file.
@implementation NSThread (FunctionExtension)
+(void)startBackgroundThreadUsingFunction:(id)object
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
void (*startThreadFunction)(void *) = (void (*)(void *))[[object objectForKey:@"function"] pointerValue];
void *startThreadData = (void *) [[object objectForKey:@"data"] pointerValue];
if(startThreadFunction != NULL) { startThreadFunction(startThreadData); }
[pool release];
pool = NULL;
}
+(void)detachNewThreadByCallingFunction:(void (*)(void *))function data:(void *)data
{
[[[[NSThread alloc] initWithFunction:function data:data] autorelease] start];
}
-(id)initWithFunction:(void (*)(void *))function data:(void *)data
{
return([self initWithTarget:[NSThread class] selector:@selector(startBackgroundThreadUsingFunction:) object:[NSDictionary dictionaryWithObjectsAndKeys:[NSValue valueWithPointer:function], @"function", [NSValue valueWithPointer:data], @"data", NULL]]);
}
@end
NOTE: I wrote the above code and here by place it in the public domain. (sometimes the lawyers like this kind of stuff) It is also completely untested!
You can always remove the NSAutoreleasePool
bits if you can guarantee that the thread entry function also creates one... but it's harmless, has no speed penalty what-so-ever, and makes calling arbitrary C functions that much more simpler. I'd say just keep it there.
And you can use it like so:
void bgThreadFunction(void *data)
{
NSLog(@"bgThreadFunction STARTING!! Data: %p", data);
}
-(void)someMethod
{
// init and then start later...
NSThread *bgThread = [[[NSThread alloc] initWithFunction:bgThreadFunction data:(void *)0xdeadbeef] autorelease];
// ... assume other code/stuff here.
[bgThread start];
// Or, use the all in one convenience method.
[NSThread detachNewThreadByCallingFunction:bgThreadFunction data:(void *)0xcafebabe];
}
When run:
2009-08-30 22:21:12.529 test[64146:1303] bgThreadFunction STARTING!! Data: 0xdeadbeef
2009-08-30 22:21:12.529 test[64146:2903] bgThreadFunction STARTING!! Data: 0xcafebabe
Создайте класс Objective-C с методом, который просто вызывает эту функцию. Возьмите селектор этого метода и передайте его NSThread
API.
Я не уверен, возможно ли это, но имейте в виду, что каждый метод Objective-C имеет два неявных / скрытых аргумента, self
и _cmd
. IMP
обычно имеет вид typedef
и выглядит так:
typedef id (*IMP)(id,SEL,...);
Если вы хотите модифицировать методы и селекторы, вам нужен метод, который выглядит так:
void func (id self, SEL _cmd, void *firstParameter);
Но даже после этого вам нужно зарегистрировать имя селектора во время выполнения, тогда вам нужно связать этот селектор с методом, но это делается для каждого класса отдельно (т.е. классы могут иметь разные реализации одного и того же селектора. name), так что вам как минимум нужен фиктивный класс.
Это много,
Если вам не нужен материал NSThread
, вы также можете запустить поток с прямым интерфейсом POSIX .