开发者

Object (holding NSMutableArray) has different content in parent/child class

I have thee classes: HopBill, HopBillController and HopBillSheetController. HopBill creates an object holding a NSMutableArray. For testing purposes I already add a row to the array in HopBill's init method. HopBillController.h has #import "HopBill.h" and the HopBillController.m initializes the object in it's awakeFromNib method: aHopBill = [[HopBill alloc] init];. So far so good. From HopBillController.m I can call methods to the aHopBill object. It retrieves the row inserted on init etc.

HopBillSheetController is a child of HopBillController and is basically a sheet that pops up after pre开发者_运维百科ssing a button. And after filling in some fields it needs to add a row to aHopBill en close the sheet. In HopBillSheetController I have:

#import "HopBillController.h"

@interface HopBillSheetController : HopBillController {

I can all methods from HopBillSheetController.m to retrieve the row inserted on init. All seems fine. However, when I fill in the fields in the sheet and press OK (in order to add a row to aHopBill) HopBillSheetController calls a method in HopBillController: [super addHopAddition: [variety stringValue]];. The row gets added, but when I retrieve all rows from aHopBill in HopBillController.m it returns only the row inserted on aHopBill's init. When I do the same from the sheet it returns the row inserted on aHopBill's init and the row I just added in the sheet.

It is as if I have two aHopBill objects, but clearly this needs to be one single object. What am I doing wrong?


You are confusing your class hierarchy with your UI object hierarchy. Inheriting from a class is not remotely the same thing as being a child window.

Your HopBillSheetController class currently inherits from HopBillController. That means it effectively has its own instance of HopBillController as its super. That instance is completely separate from the one associated with your window. Changes to one will not affect the other, as you've found.

This is not what you want at all. You want to associate the actual objects, not the class structure. How you go about it depends on how the whole setup is created and structured, but it probably comes down to one or other of these options:

  • If you're putting the UI together in Interface Builder (or whatever we call that nowadays), you need to put in appropriate IBOutlet instance variables into your classes and make connections between them using the UI tools.

  • If you're making the connections in code, you need to add properties (or other suitable accessor methods) so that the code in one class can get at the necessary object instances in the other.

Either way, you should lose the spurious inheritance between the two classes.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜