Objective-C 中不帶加減號的方法
- 2021 年 5 月 26 日
- 筆記
顯而易見的事實是,Objective-C 中, 但看別人程式碼過程中,還會發現一種,不帶加減號的方法。 @implementation MyViewController
void foo(){
printf("msg from foo...");
}
- (void)loadView {
[super loadView];
foo();
}
@end
這種是混搭的 C 程式碼。 當然當 C 方法寫在 void foo(){
printf("msg from foo...");
}
@implementation MyViewController
- (void)loadView {
[super loadView];
foo();
}
@end
C 中獲取 Objective-C 的數據但如果你以為將 C 程式碼寫在 MyViewController.h @interface MyViewController ()
@property NSString *someStr;
@end
MyViewController.m @implementation MyViewController
// void foo() { printf(self.someStr); } // 🚨 Use of undeclared identifier '_someStr'
void foo() { printf(_someStr); } // 🚨 Use of undeclared identifier '_someStr'
- (void)loadView {
[super loadView];
self.someStr = @"some string...";
foo();
}
@end
正確的做法是將 Objective-C 的對象傳遞給 C 程式碼,這樣在 C 中便有了一個對象的引用,數據就可以正常獲取了。 MyViewController.h @interface MyViewController : UIViewController
@property NSString *someStr;
- (void)myObjcMethod;
@end
MyViewController.m void foo(MyViewController* obj) {
printf("%s\n", [obj.someStr UTF8String]);
[obj myObjcMethod];
}
@implementation MyViewController
- (void)loadView {
[super loadView];
self.someStr = @"some string...";
foo(self);
}
- (void)myObjcMethod {
NSLog(@"msg from my objc method");
}
@end
相關資源 |
The text was updated successfully, but these errors were encountered: |