我希望标题足够精确。 我想知道如何将接口实现传递给objc语言的对象。
在java中它看起来像:
public interface MyInterface {
void onData();
}
实施班级
public class ImplementMyInterface {
// ...
// other methods
///
void registerInterface(){
MyInterface myInterface = new MyInterface(){
@Override
public void onData(){
// process data here within the class
}
};
}
}
在objc? id myinterface。
如何在课堂上实现它? 是否只有让类继承接口的可能性? 喜欢
interface MyInterface : NSObject
和实施类
MyImplementingClass : MyInterface
或者还有其他可能吗? 提前谢谢
答案 0 :(得分:0)
Objective-C has anonymous functions (blocks), but it doesn't have anonymous classes. So, the only way to implement a protocol (which is the objective-c term for an interface) is to make some class conform to that protocol (using your terminology, make that class "inherit" from that protocol) and add a protocol implementation inside that class' implementation.
答案 1 :(得分:0)
我能够解决我的问题。 我只能够在我的ImplementMyInterface.m文件中导入MyInterface头文件,而只能在ImplementMyInterface.h文件中导入。 因此,我所能做的都是在ImplementMyInterface.m文件中。
// ImplementMyInterface.m
#import "MyInterface.h"
// inner class
@interface MyInternalInterface : NSObject<MyInterface>
@property (retain) ImplementMyInterface * implementation;
@end
// the actual class
@implementation ImplementMyInterface
MyInternalInterface * _internalInterface;
+(instancetype) build {
// construct myself
ImplementMyInterface * implementatMyInterface = [[ImplementMyInterface alloc] init];
// init inner class object
_internalInterface = [[MyInternalInterface alloc] init];
// register myself
[_internalInterface setImplementation:implementatMyInterface];
return implementatMyInterface;
}
- (NSString *) theActualData {
return @"The actual data";
}
// end of implementation class
@end
// implementation of inner class
@implementation MyInternalInterface
@synthesize implementation;
- (NSString *) onData {
if(implementation != nil)
return [implementation theActualData];
return @"";
}
// end of ImplementMyInterface.m