顯而易見的事實是,Objective-C 中,+
表示類方法,-
表示實例方法。
但看別人代碼過程中,還會發現一種,不帶加減號的方法。
@implementation MyViewController
void foo(){
printf("msg from foo...");
}
- (void)loadView {
[super loadView];
foo();
}
@end
這種是混搭的 C 代碼。
當然當 C 方法寫在 @implementation
內也是可以的,編譯器會正確地處理。因為 C 方法嚴格來說不隸屬於類,好的做法是始終寫在類實現的外部。
void foo(){
printf("msg from foo...");
}
@implementation MyViewController
- (void)loadView {
[super loadView];
foo();
}
@end
C 中獲取 Objective-C 的數據
但如果你以為將 C 代碼寫在 @implementation
內部就可以獲取到類里面的數據,那是不現實的。
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: