【问题标题】:How to access @private instance variable using category in Objective-C?如何在 Objective-C 中使用类别访问 @private 实例变量?
【发布时间】:2011-11-02 17:41:49
【问题描述】:

正如 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] 在 NSString+Utilities.o ld:未找到体系结构 i386 的符号 collect2: ld 返回 1 个退出状态

【问题讨论】:

  • 你试过加#import &lt;UIKit/UIKit.h&gt;吗?
  • 我刚刚添加到我的 NSString+Utilities.h 中。但是,同样的错误仍然存​​在。

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


【解决方案1】:

由于您在代码中向 NSString 类 length 添加方法,因此将替换为 self.length.

【讨论】:

  • 抱歉,我上一个 NSString 示例不是一个好示例。我使用 UITextField 更新了一个新示例。
【解决方案2】:

NSString 没有变量名长度:

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

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

【讨论】:

    猜你喜欢
    • 2012-01-23
    • 2014-03-16
    • 2011-05-07
    • 1970-01-01
    • 2011-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-02
    相关资源
    最近更新 更多