如何在 Objective-C 中使用类别访问 @private 实例变量?
请注意,类别不能为该类声明额外的实例变量;它仅包含方法。然而,类范围内的所有实例变量也都在类别范围内。这包括类声明的所有实例变量,甚至是声明为 @private 的实例变量。
但是,当我尝试访问 UITextField“_selectionRange”的私有实例变量时,出现符号未找到错误。下面是我的源码和错误信息,供大家参考。我对那些阅读我的最后一个示例“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 架构的未定义符号: “_OBJC_IVAR_$_UITextField._selectionRange”,引用自: -NSString+Utilities.o 中的[UITextField(编辑)deleteBkw] ld:未找到架构 i386 的符号 Collect2: ld 返回 1 退出状态
As it states in the Apple's documentation: http://developer.apple.com/library/mac/#documentation/cocoa/Conceptual/ObjectiveC/Chapters/ocCategories.html#//apple_ref/doc/uid/TP30001163-CH20-SW1
Note that a category can’t declare additional instance variables for the class; it includes only methods. However, all instance variables within the scope of the class are also within the scope of the category. That includes all instance variables declared by the class, even ones declared @private.
However, when I tried to access a private instance variable of UITextField "_selectionRange" I get symbol not found error. Below are my source code and error message for your reference. I apologize for those who read my last example "NSString". It wasn't a good example since there isn't any @private instance variables in NSString class.
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
Error:
Undefined symbols for architecture i386:
"_OBJC_IVAR_$_UITextField._selectionRange", referenced from:
-[UITextField(Editing) deleteBkw] in NSString+Utilities.o
ld: symbol(s) not found for architecture i386
collect2: ld returned 1 exit status
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
NSString 没有变量名称长度:
因此,您可以通过调用 [self length] 来访问 length 方法(而不是变量),并且只能通过这种方式。
NSString has no variables name length:
So you can access to the length method (and not variable) by calling [self length] and only by this way.
由于您要向代码中的 NSString 类
length
添加方法,因此将替换为self.length。
Since you're adding methods to NSString class
length
in your code is to replaced byself.length.