Last active
June 13, 2019 09:34
-
-
Save CS2Us/7c43c1e51b9bc475c73967f31153bbf1 to your computer and use it in GitHub Desktop.
Undefined behavior:Objective-C category
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
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
Objective-C Category make program behavior undefined: it's so ridiculous as support change
TestCls
type toNSString
!!!!