The method without plus minus sign in Objective-C
Liu wayong 2021-06-14 13:24:54

The obvious fact is ,Objective-C in ,+ Represent class methods ,- Represent instance method .

But looking at other people's code , And there's a kind of , The method without plus minus sign .

@implementation MyViewController
void foo(){
printf("msg from foo...");
}
- (void)loadView {
[super loadView];
foo();
}
@end
 

This is a mix and match C Code .

Of course C The method is written in @implementation It's OK to be inside , The compiler will handle . because C Methods are not strictly part of a class , It's good to always write outside the class implementation .

void foo(){
printf("msg from foo...");
}
@implementation MyViewController
- (void)loadView {
[super loadView];
foo();
}
@end
 

C In order to get Objective-C The data of

But if you think it's going to be C The code is written in @implementation The data in the class can be obtained internally , That's not realistic .

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
 

The right thing to do is to Objective-C Is passed to C Code , In this way C There is a reference to an object in , Data can be obtained normally .

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
 

Related resources

The text was updated successfully, but these errors were encountered:

Please bring the original link to reprint ,thank
Similar articles