开发者

Sending data between classes

I seem to be missing a key fundamental concept on sending data between two classes. I read another post on here, and I'll comment on开发者_Python百科 that in a sec, but here is what I have. In a custom view class, I got a NSMutableDictionary that is working fine and is retained:

@interface myView : UIView {
}

@property (nonatomic, retain) NSMutableDictionary*myDictionary;

The methods in myView use myDictionary with no problem. For example, I can do this fine:

 NSArray*sorted=[[NSArray alloc] initWithArray:[self.myDictionary keysSortedByValueUsingSelector:@selector(compare:)]];

In my view controller, I am then trying to create a similar array using the same data in the myDictionary object from the custom class:

@interface myViewController : UIViewController {

}

@property (nonatomic, retain) IBOutlet myView * myView;

Then later I have:

  NSArray*sorted=[[NSArray alloc] initWithArray:[self.myView.myDictionary keysSortedByValueUsingSelector:@selector(compare:)]];

However, this myDictionary is always empty. It is not released anywhere in myView so it should still contain data. I've tried removing "self" with no luck.

Now, I read this similar post:

Data not sending between classes - Objective-C

Is this the only method for doing something like this? This implies that you must "send" the data from the source class to the receiving class. It suggests that you cannot have the receiving class "go fetch" the data from the source class as I am here. Is that right? More importantly, if that is the only method, then why so?


Triple-check your outlet connections! Then check them again.

When you hook up an IBOutlet through Interface Builder, you have a real, instantiated object at the other end. You can access the properties of that object just as you would with any other object:

self.myView.hidden = NO;

If you assign a new object to that outlet:

self.myView = [[MyCustomViewClass alloc] initWithFrame:someRect];

you lose track of the view that was created for you in the xib, and when you try to access ivars of that new view:

NSDictionary * aDict = self.myView.myDictionary;

they will not have the same values as the ivars of the other view that is in the xib (they will probably be nil, in fact).

It's perfectly all right for data to be passed in either direction. You just need to have the appropriate references. The view can "send" to the controller, but it needs to have a reference to that controller set up:

// Get a reference to view controller somehow
self.myController = ...;
[self.myController setArray:[self.myDictionary keys...]];

Since controllers generally have references to their views, it probably makes more sense to go the other way, as you're already doing.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜