Objective-C 中不带加减号的方法
字数:240,预计阅读时间:1min
显而易见的事实是,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: |

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步