请注意,类别不能为该类声明额外的实例变量;它仅包括方法。但是,类范围内的所有实例变量也都在类的范围内。这包括类声明的所有实例变量,甚至是声明为@private 的实例变量。
但是,当我尝试访问 UITextField“_selectionRange”的私有(private)实例变量时,出现符号未找到错误。以下是我的源代码和错误信息供您引用。对于那些阅读我上一个示例“NSString”的人,我深表歉意。这不是一个很好的例子,因为在 NSString 类中没有任何@private 实例变量。
NSString+Utilities.h
#import <Foundation/Foundation.h>
@interface UITextField (Editing)
- (void)deleteBkw;
@end
NSString+Utilities.m
@implementation UITextField (Editing)
- (void)deleteBkw {
NSLog(@"%d:%d", _selectionRange.location, _selectionRange.length);
}
@end
错误: 架构 i386 的 undefined symbol : “_OBJC_IVAR_$_UITextField._selectionRange”,引用自: -[UITextField(Editing) deleteBkw] in NSString+Utilities.o ld:未找到架构 i386 的符号 collect2: ld 返回 1 个退出状态
最佳答案
NSString 没有变量名长度:
The NSString class has two primitive methods—length and characterAtIndex:—that provide the basis for all other methods in its interface. The length method returns the total number of Unicode characters in the string. characterAtIndex: gives access to each character in the string by index, with index values starting at 0.
因此您可以通过调用 [self length] 访问 length 方法(而不是变量),并且只能通过这种方式。
关于objective-c - 如何在 Objective-C 中使用类别访问@private 实例变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7174765/