簡體   English   中英

如何在目標c框架函數中將可選依賴項的參數作為參數傳遞

[英]How to pass arguments of optional dependencies as params in objective c framework function

我正在開發一個目標c框架供其他開發人員使用。

在這個框架中,我想使用其他框架中的可用類(如果它們可用)。

例如,目前我正在使用AdSupport.framework(如果可用 - 由應用程序開發人員鏈接),采用以下方法:

if (NSClassFromString(@"ASIdentifierManager")) {
        NSString adString = [[[NSClassFromString(@"ASIdentifierManager") sharedManager] advertisingIdentifier] UUIDString];
}

但是現在,我希望我的框架的公共函數的參數包含可選依賴項的類,我無法做到這一點。

例如:

我想要一個功能:

+ (void) sendLocation: (CLLocation *) myLoc;

但CoreLocation.framework可以選擇性地鏈接,也許不適用於應用程序。 如何使用上面的AdSupport.framework采用類似的方法?

我以為我可以這樣做:

+ (void) sendLocation: (NSClassFromString(@"CLLocation") *) myLoc; 

要么

+ (void) sendLocation: (id) myLoc; 

要么

+ (void) sendLocation: (Class) myLoc; 

然后以某種方式提取坐標,但無法實現。 最后一個選項(Class)似乎編譯但我找不到提取params的方法..

任何人都可以幫忙嗎?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM