我正在开发一个 Objective-C 框架,供其他开发人员使用。
在这个框架中,我想使用其他框架中可用的类(如果它们可用的话)。
例如,目前我正在通过以下方法使用 AdSupport.framework(如果可用 - 由应用开发人员链接):
if (NSClassFromString(@"ASIdentifierManager")) {
NSString adString = [[[NSClassFromString(@"ASIdentifierManager") sharedManager] advertisingIdentifier] UUIDString];
}
但是现在,我想让我的框架的公共(public)函数的参数包含可选依赖项的类,但我无法做到这一点。
例如:
我想要一个函数:
+ (void) sendLocation: (CLLocation *) myLoc;
但 CoreLocation.framework 将被选择性地链接并且可能不适用于应用程序。我如何才能对上述 AdSupport.framework 采用类似的方法?
我以为我可以做这样的事情:
+ (void) sendLocation: (NSClassFromString(@"CLLocation") *) myLoc;
或
+ (void) sendLocation: (id) myLoc;
或
+ (void) sendLocation: (Class) myLoc;
然后以某种方式提取坐标但无法实现。最后一个选项(类)似乎可以编译,但我找不到提取参数的方法..
有人可以帮忙吗?
最佳答案
MapKit 的简短示例(除非您请求,否则不会链接到您的应用)
标题:
@class MKMapView;
@interface MyTestInterface : NSObject
+ (void)printMapViewDescription:(MKMapView *)mapView;
@end
执行文件:
#import "MyTestInterface.h"
#import <MapKit/MapKit.h>
@implementation
+ (void)printMapViewDescription:(MKMapView *)mapView {
if ((NSClassFromString(@"MKMapView")) {
NSLog(@"%@", mapView);
} else {
NSLog(@"MapKit not available");
}
}
@end
所以你链接到内部的标题。这仅在您提供二进制文件或仅使用 apple-frameworks 时才有效。如果您提供源代码并且想要与第三方框架交互,则必须使用 performSelector、NSInvocation 或匿名对象 (id) 上的 objc-runtime。
编辑:
NSInvocation 示例
标题:
@class MKMapView;
@interface MyTestInterface : NSObject
+ (void)printMapViewFrame:(MKMapView *)mapView;
@end
执行文件:
#import "MyTestInterface.h"
@implementation
+ (void) printMapViewFrame:(id)mapView {
if ([mapView respondsToSelector:@selector(frame)]) {
NSMethodSignature *sig = [mapView methodSignatureForSelector:@selector(frame)];
if (sig) {
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig];
[invocation setTarget: mapView];
[invocation setSelector:@selector(frame)];
[invocation invoke];
CGRect rect;
[invocation getReturnValue:&rect];
NSLog(@"%@", NSStringFromCGRect(rect));
}
}
}
@end
关于ios - 如何在 objective-c 框架函数中将可选依赖项的参数作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36182587/