iPhone - NSObject getting reference to viewController
开发者_StackOverflow社区I have this object of NSObject class. This object is shown on a view managed by a viewController. How do I get a reference to that viewController from inside the object's class?
There is no "myViewController" property as you know. The easiest way to give any object access to some other object is through a delegate relationship.
Define a protocol for the delegate - typically in the module that wants access to the object which will be the delegate, i.e. the view controller
@protocol MyViewControllerDelegate
- (void)someActionTheViewControllerWillDo;
#end
Advertise the delegate support in the class implementing it
@interface MyViewController : UIViewController <MyViewControllerDelegate>
...
@end
Implement the function you defined as being part of the protocol in the view controller:
@implementation MyViewController
etc. etc.
#pragma mark -
#pragma mark MyViewControllerDelegateMethods
- (void)someActionTheViewControllerWillDo
{
NSLog(@"I'm being called from an object that has me as a delegate");
}
etc. etc.
@end
Make a variable in the calling object to store the delegate object
@interface MyObject : NSObject
{
etc. etc.
id<MyViewControllerDelegate> myDelegate;
etc. etc.
}
Initialize that object
MyObject* myObject = [[MyObject alloc] initWithblahblah...
myObject.myDelegate = self
/* assuming myObject is being created in the view controller... */
In myObject - use the defined protocol to access methods in the delegate object!
[myDelegate someActionTheViewControllerWillDo];
User delegate pattern:
0 . Declare a protocol:
@protocol My_Object_Delegate;
1.Give your NSObject an instance variable:
id <My_Object_Delegate> delegate;
2 . Set this delegate the view controller that supervise it:
myObject.delegate = myViewController;
3 . When your NSObject is done. Let it ask its delegate to perform certain task:
[myObject.delegate performaCertainTask:self];
精彩评论