Objective-C - 混合协议和类别

时间:2022-09-07 07:41:36

In Swift, you could do something like this:

在Swift中,你可以这样做:

protocol Archivable: class {
}

extension UserDefaults: Archivable { }

Is there an equivalent in Objective-C to make NSUserDefaults conform to a protocol?

Objective-C中是否有等效的NSUserDefaults符合协议?

2 个解决方案

#1


0  

Yes, you can do it in Objective-C

是的,您可以在Objective-C中完成

@protocol Archivable

- (void)doSomething;

@end

@interface NSUserDefaults (Test)<Archivable>

@end

@implementation NSUserDefaults (Test)

- (void)doSomething {
  NSLog(@"Do something");
}

@end

Try to use

尝试使用

[NSUserDefaults.standardUserDefaults doSomething];

Result

Do something

#2


0  

Yes, you can make a new category of NSUserDefaults, and confirm your protocol and implement protocol methods in the category file.

是的,您可以创建一个新类别的NSUserDefaults,并在类别文件中确认您的协议并实现协议方法。

#1


0  

Yes, you can do it in Objective-C

是的,您可以在Objective-C中完成

@protocol Archivable

- (void)doSomething;

@end

@interface NSUserDefaults (Test)<Archivable>

@end

@implementation NSUserDefaults (Test)

- (void)doSomething {
  NSLog(@"Do something");
}

@end

Try to use

尝试使用

[NSUserDefaults.standardUserDefaults doSomething];

Result

Do something

#2


0  

Yes, you can make a new category of NSUserDefaults, and confirm your protocol and implement protocol methods in the category file.

是的,您可以创建一个新类别的NSUserDefaults,并在类别文件中确认您的协议并实现协议方法。