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]並且只能通過這種方式。