Skip to content

Instantly share code, notes, and snippets.

@CS2Us
Last active June 13, 2019 09:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CS2Us/7c43c1e51b9bc475c73967f31153bbf1 to your computer and use it in GitHub Desktop.
Save CS2Us/7c43c1e51b9bc475c73967f31153bbf1 to your computer and use it in GitHub Desktop.
Undefined behavior:Objective-C category
#import <Foundation/Foundation.h>
@interface TestCls: NSObject
@property(nonatomic, copy) NSString *name;
@end
@implementation TestCls
- (instancetype)init {
if (self = [super init]) {
[self testFunction];
}
return self;
}
- (void)testFunction {
NSLog(@"testFunction %@", self.name);
}
@end
@interface TestCls (TestCategory)
- (void)testFunction;
@end
@implementation TestCls (TestCategory)
- (void)testFunction {
NSLog(@"another testFunction");
}
- (Class)class {
return [NSString class];
}
@end
int main() {
TestCls *testCls = [[TestCls alloc] init];
[testCls testFunction];
NSLog(@"which class is testCls %@", [testCls class]);
NSString *testStr = @"testStr";
NSLog(@"which class is testStr %@", [testStr class]);
}
@implementation NSString (Test_Category)
- (Class)class {
return [NSNumber class];
}
@end
import Foundation
class TestCls: NSObject {
var name: String
var anothername: String
override init() {
self.name = ""
self.anothername = ""
super.init()
}
func testFunction() {
print("testFunction")
}
}
protocol TestPrtl {
func testFunction()
}
extension TestPrtl {
func testFunction() {
print("another testFunction")
}
}
extension TestCls: TestPrtl {
/* compiler will report error:
* Invalid redeclaration of 'testFunction()' **/
/* If we comment testFunction below to resolve compiler error
* program run well but the console whill log "testFunction" instead of "another testFunction" **/
func testFunction() {
}
}
let testCls = TestCls()
testCls.testFunction()
@CS2Us
Copy link
Author

CS2Us commented Jun 13, 2019

Objective-C Category make program behavior undefined: it's so ridiculous as support change TestCls type to NSString!!!!

@CS2Us
Copy link
Author

CS2Us commented Jun 13, 2019

On the opposite way, Swift is more Safe, even though we implementation ```TestPrtl``, and default implementation of testFunction not be changed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment