如何在Objective-C中使用category访问@private实例变量



正如Apple的文档中所述: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.

然而,当我试图访问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",引用自:-[UITextField(Editing) deleteBkw] in NSString+Utilities.o在体系结构i386中找不到Ld:符号

NSString没有变量名称长度:

NSString类有两个基本方法——length和characterAtIndex——它们为接口中的所有其他方法提供了基础。length方法返回字符串中Unicode字符的总数。characterAtIndex:通过索引访问字符串中的每个字符,索引值从0开始。

所以你可以通过调用[self length]来访问length方法(而不是变量),并且只能通过这种方式。

既然你在代码中添加NSString类length的方法是由self.length.

最新更新