开发者

How to pass a variable between two classes in Cocoa?

开发者 https://www.devze.com 2023-02-28 14:08 出处:网络
I\'m a newbie to Cocoa and Objective-开发者_JS百科C. I\'m currently working on a program that will generate a grid in a CustomView. For this, I have a control window (with all the sliders/options) and

I'm a newbie to Cocoa and Objective-开发者_JS百科C. I'm currently working on a program that will generate a grid in a CustomView. For this, I have a control window (with all the sliders/options) and a preview window (that draws the grid). These two windows are attached to different classes: the control window to the GridPaperController class, and the preview window to the GridView class.

Let's say I change a slider on my control window. The label next to it changes with its value (which is stored as a variable in the GridPaperController class). How can I send this value to the GridView class?

Thanks for the help.


There are a couple of patterns to passing information between unrelated classes. You could create a delegate between your controller and the two other view controllers. This method is very nice because it is highly cohesive and decreases coupling between your classes.

A second way is to post notifications so that messages can be sent for classes waiting for events/information. This, again, is a pattern that decreases coupling between unrelated classes.


You can add setter's to your class:

@interface Photo : NSObject 
{ 
    NSString* caption;
    NSString* photographer; 
} 

- (void) setCaption: (NSString*)input; 
- (void) setPhotographer: (NSString*)input; 

@end 

And the methods implementation:

- (void) setCaption: (NSString*)input 
{   
    [caption autorelease]; 
    caption = [input retain]; 
} 

- (void) setPhotographer: (NSString*)input 
{ 
    [photographer autorelease]; 
    photographer = [input retain]; 
}
0

精彩评论

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