NSString、UIView)添加方法。@protocol 不支持可選方法時的替代方案)。類 Person 在 .m 文件的 @interface Person() 擴展中聲明了私有方法 getName。外部類直接調用 [Person getName] 會編譯報錯:No known class method for selector 'getName'。
// Person+Private.h
#import "Person.h"
@interface Person (Private)
+ (void)getName; // 僅聲明,無需實現
@end
在調用處 #import "Person+Private.h" 後,編譯器知曉 getName 存在,不再報錯。運行時動態綁定會找到 Person.m 中的實際實現並執行。
// Person.h
#import <Foundation/Foundation.h>
@interface Person : NSObject
+ (void)getAge;
@end
// Person.m
#import "Person.h"
@interface Person ()
+ (void)getName; // 私有方法聲明
@end
@implementation Person
+ (void)getAge { NSLog(@"age:18"); }
+ (void)getName { NSLog(@"name:XXX"); }
@end
// Person+Private.h (Category)
#import "Person.h"
@interface Person (Private)
+ (void)getName; // 前向引用聲明
@end
// Caller.m
#import "Person+Private.h"
@implementation Caller
- (void)test {
[Person getName]; // 不再報錯,運行輸出 "name:XXX"
}
@end
objc_setAssociatedObject 模擬)。xxx_getName。