开发者

Storing callbacks in a dictionary (Objective C for the iPhone)

开发者 https://www.devze.com 2022-12-17 02:20 出处:网络
I am trying to store callbacks in a dictionary. I can\'t use blocks as the iPhone doesn\'t support this (unless you use plblocks).

I am trying to store callbacks in a dictionary.

  • I can't use blocks as the iPhone doesn't support this (unless you use plblocks).
  • I tried using functions, bu开发者_如何转开发t apparently NSMutableDictionary doesn't allow these pointers (wants an id)
  • I tried using class methods, but I couldn't find a way to obtain a pointer to these
  • I could try using functions with the c++ stl hashmap (if it is supported in Objective C++), but apparently this can slow compilation times.
  • I could try storing both a class and a selector, but that seems rather messy.

What would be the best way to do this?


You can put it in an NSInvocation.

An NSInvocation is an Objective-C message rendered static, that is, it is an action turned into an object. NSInvocation objects are used to store and forward messages between objects and between applications, primarily by NSTimer objects and the distributed objects system.


If you know what you are doing with pointers, you can wrap them up with NSValue. You can then put NSValue in a dictionary.

To insert:

[myDict setObject:[NSValue valueWithPointer:functionName] forKey:myKey];

For retrieval:

NSValue* funcVal=(NSValue*) [myDict objectForKey:myKey];
returnType* (*func)()=[funcVal pointerValue];


If it's your own project, why not use blocks since you can?


It is possible to make a single file compile using C++ if you change the extension to .mm. You don't have to change the other files in your project as long as they don't have to handle any C++ types.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号