objective-c - 如何在 Objective-C 中使用类别访问@private 实例变量?

标签 objective-c ios categories instance-variables private-members

正如 Apple 文档中所述:http://developer.apple.com/library/mac/#documentation/cocoa/Conceptual/ObjectiveC/Chapters/ocCategories.html#//apple_ref/doc/uid/TP30001163-CH20-SW1

请注意,类别不能为该类声明额外的实例变量;它仅包括方法。但是,类范围内的所有实例变量也都在类的范围内。这包括类声明的所有实例变量,甚至是声明为@private 的实例变量。

但是,当我尝试访问 UITextField“_selectionRange”的私有(private)实例变量时,出现符号未找到错误。以下是我的源代码和错误信息供您引用。对于那些阅读我上一个示例“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 的 undefined symbol : “_OBJC_IVAR_$_UITextField._selectionRange”,引用自: -[UITextField(Editing) deleteBkw] in NSString+Utilities.o ld:未找到架构 i386 的符号 collect2: ld 返回 1 个退出状态

最佳答案

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] 访问 length 方法(而不是变量),并且只能通过这种方式。

关于objective-c - 如何在 Objective-C 中使用类别访问@private 实例变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7174765/

相关文章:

ios - 替换 iOS 9 中的 NSAttributedString initWithFileURL

objective-c - 如何在 .h 文件中写入具有多个参数的方法的名称

ios - 为什么 Apple 使用不同的文件夹结构来进行 bundle 和字符串本地化?

ios - 将 UILabel 拉伸(stretch)到 UICollectionViewCell 的全宽

ios - 单元目标测试构建失败 xcode objective-c

ios - NSFileHandle fileHandleForWritingAtPath 返回 nil 和有效路径

objective-c - 跨 Cocoa 应用程序共享数据

iphone - 向 NSArray 添加类别

iphone - NSObject 上的类别——保证它的安全

php - 如何在特定管理页面上显示magento的所有创建的类别?