IOS class method

@interface TestObj :NSObject
@property(copy, nonatomic)NSString *name;
@end
@implementation TestObj
- (void)testName{

  NSLog(@"name:%@",self.name);

}
@end 

@interface ViewController ()
@end

@implementation ViewController
- (void)viewDidLoad {

  [super viewDidLoad];

  id tclass =[TestObj class];

  void * vid = &tclass;

  [(__bridge id)vid testName];

}
@end

log:

 name: <ViewController: 0x7ff3584b6580>

My understanding vidis a pointer to the address of a class object TestObj, why vidcan it be sent directly to the instance method testName?

Also, why does the method testNamecall NSLogoutput <ViewController: 0x7ff3584b6580>instead of nil?

Thank.

+4
source share
1 answer

I think you are mostly lucky that you are not down with this code.

First, class methods start with +not a -- so this is the instance method that you implement.

@interface TestObj :NSObject
@property(copy, nonatomic)NSString *name;
@end
@implementation TestObj
+ (void)testName{
NSLog(@"name:%@", @"TestObj"); // cannot reference ivars or properties in class method
}
@end
...
Class classObject = [TestObj class];
[classObject testName];

( ). Objective-C , , "isa", . "Isa" "", , . TestObj, , TestObj, - , . , - ( ) , "" . , , , a -name NSString , UIViewController. , , , , ViewController . , -name, .

, tl; dr - ( ), , . (bridge id) , .

+1

Source: https://habr.com/ru/post/1656299/


All Articles