关于私有变量的访问

我在学习书上的实践编的第一个MobileNotes遇到一个问题,按照书上的类子编写的代码在文字改变时会crash,通过定位发现是contentLayer这个对象找不到的原因。我查看了头文件,我的iOS7的如下,是有这个变量的。
@interface NotesDisplayController : ResumableViewController <UITextViewDelegate, NoteContentLayerDelegate, NotesFindViewControllerDelegate, NotePresenter, UIActionSheetDelegate, AFContextProvider, UIPopoverControllerDelegate>
{
id _delegate;
NotesBackgroundView *_backgroundView;
UIBarButtonItem *_deleteButtonItem;
UIBarButtonItem *_shareButtonItem;
UIBarButtonItem *_doneButton;
UIBarButtonItem *_addButton;
NoteObject *_note;
int _noteIndexToDisplayAfterDelete;
**NoteContentLayer *_contentLayer;//就是这个变量,书本上是通过设置属性

  • @property(retain,nonatomic)NoteContentLayer* contentLayer;来访问这个变量的,可是我运行时crash。**

。。。。。。
}

然后我就摸索想通过如下方法获取私有变量:
Ivar ivar = class_getInstanceVariable([self class], “_contentLayer”);
NoteContentLayer* contentLayer = object_getIvar(self, ivar);

可结果还是crash,我就苦恼了,难道是这个类里没有contentLayer属性吗?class-dump出来的头文件里有这个变量啊,还是我用的不对啊,请老大点播下。

下面是我申明NotesDisplayController这个类的代码:
@interface NotesDisplayController : UIViewController
@property(retain,nonatomic)NoteContentLayer* contentLayer;
@property(retain,nonatomic)NoteObject* note;
@end

//更新文字总数

  • (void)noteContentLayerContentDidChange:(NoteContentLayer *)arg1 updatedTitle:(BOOL)arg2
    {
    %orig;

    NSString* content = self.contentLayer.textView.text;
    NSString* contentLength = [NSString stringWithFormat:@"%lu",(unsigned long)[content length]];
    self.title = contentLength;

}

我看了下,iOS 7里只有一个静态变量
NoteContentLayer* _contentLayer;
没有property,所以你要访问的话,只能通过object_getInstanceVariableMSHookIvar来获取,而不是用class_getInstanceVariable或者getter

好的,我试试,另外大神刚说用hook的方法获取私有变量,这个大概怎么hook呢,难道hook它的get方法?可私有变量没有get属性啊,还请大神继续点拨下。

MSHookIvar是CydiaSubstrate提供的访问私有变量的函数,你google一下就知道用法了

1 个赞

好的,多谢