3

正如苹果的文档中指出:http://developer.apple.com/library/mac/#documentation/cocoa/Conceptual/ObjectiveC/Chapters/ocCategories.html#//apple_ref/doc/uid/TP30001163-CH20-SW1如何使用Objective-C中的类别访问@private实例变量?

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”,从引用: - NSString + Utilities.o中的[UITextField(Editing)deleteBkw] ld:找不到架构i386的符号 collect2:ld返回1退出状态我们

+0

你试过添加'#import '吗? –

+0

我刚添加到我的NSString + Utilities.h中。但是,同样的错误仍然存​​在。 – docchang

回答

0

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

+0

对不起,我最后的NSString例子不是很好。我已经使用UITextField更新了一个新示例。 – docchang

5

的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]并且只能通过这种方式。