开发者

How to access @private instance variable using category in Objective-C?

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;
@e开发者_如何转开发nd

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


NSString has no variables name length:

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.

So you can access to the length method (and not variable) by calling [self length] and only by this way.


Since you're adding methods to NSString class length in your code is to replaced by self.length.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜