Why isn't there performSelectorOnMainThread: in NSObject Protocol? - iphone

Recently I'm working on app. project for iPhone(iOS).
I wonder why there isn't performSelectorOnMainThread: in NSObject Protocol.
I need to call to delegate's methods on main thread 'cause they have to handle UI components.
Here's sample I wrote:
#protocol MyOperationDelegate;
#interface MyOperation : NSOperation {
id <MyOperationDelegate> delegate;
}
#property (nonatomic, assign) id <MyOperationDelegate> delegate;
#end
#protocol MyOperationDelegate <NSObject>
#optional
- (void) didFinishHandleWithResult:(NSDictionary *)result;
#end
#implementation MyOperation
#synthesize delegate;
- (void) main {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSDictionary *aDict = [[MySingleton sharedObject] fetchSomethingMeaningful];
//do something and call delegate
if ([delegate respondsToSelector:#selector(didFinishHandleWithResult:)]) {
[delegate performSelector:#selector(didFinishHandleWithResult:) withObject:
}
[pool release];
}
#end
#interface MyViewCon : UIViewController <MyOperationDelegate> {
NSOperationQueue *queue;
}
#end
#implementation MyViewCon
- (void) viewDidLoad {
MyOperation *op = [[MyOperation alloc] init];
op.delegate = self;
[queue addOperation:op];
[op release];
}
- (void) reloadUserInterface:(NSDictionary *)dict {
// Do reload data on User Interfaces.
}
- (void) didFinishHandleWithResult:(NSDictionary *)myDict {
// Couldn't execute method that's handling UI, maybe could but very slow...
// So it must run on main thread.
[self performSelectorOnMainThread:#selector(reloadUserInterface:) withObject:myDict];
}
#end
Can I run didFinishHandleWithResult: delegate method on main thread in MyOperation class?
Since here I am implementing UI handling method every time I call MyOperation instance.
Any suggestion will be helpful for me.

Let's try:
dispatch_async(dispatch_get_main_queue(), ^{
//your main thread code here
});

NSObject does have a method performSelectorOnMainThread:withObject:waitUntilDone. You can use that.

Yes you can make use of the method like this
[delegate performSelectorOnMainThread:#selector(reloadUserInterface:) withObject:myDict waitUntilDone:YES];

Related

Objective-c multiple delegates in the same view - ECSlidingViewController

I started testing ECSlidingViewController and after I tried to access FirstTopViewController I have a big trouble - because in FirstToViewController I already have ZBarReaderDelegate implemented and all examples of delegate are not triggering any method from my delegate.
Basically I have this stuff:
FirstTopViewController.h
#import ...MyStuff...
#import "UnderRightViewController.h"
#interface FirstTopViewController : UIViewController <RightViewDelegate, ZBarReaderDelegate>
#property (weak, nonatomic) IBOutlet UITextView *labelTotal;
#end
FirstTopViewController.m
#import "FirstTopViewController.h"
#implementation FirstTopViewController
- (void)setTotalViewController:(UnderRightViewController*)controller didTotalChange:(NSString*)total
{
//labelTotal.text = total;
NSLog(#"I'm here!!! and received %#", total);
}
From other side I have
UnderRightViewController.h
#import <UIKit/UIKit.h>
#import "ECSlidingViewController.h"
#class UnderRightViewController;
#protocol RightViewDelegate <NSObject>
- (void)setTotalViewController:(UnderRightViewController*)controller didTotalChange:(NSString*)total;
#end
#interface UnderRightViewController : UITableViewController
#property (nonatomic, weak) id <RightViewDelegate> delegate;
#end
UnderRightViewController.m
#import "UnderRightViewController.h"
#interface UnderRightViewController ()
#end
#implementation UnderRightViewController
#synthesize delegate;
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[delegate setTotalViewController:self didTotalChange:#"foo"];
}
#end
I'm trying this entire day solve this puzzle but I never get setTotalViewController fired.
Thanks in advance.
Friend you did a small mistake, when you navigate from FirstTopViewController to UnderRightViewController at that time you need to do this in FirstTopViewController.m:-
UnderRightViewController *obj = [[UnderRightViewController
alloc] initWithNibName:#"UnderRightViewController" bundle:nil];
obj.delegate = self; // u forget to assign protocol handler
[self.navigationController pushViewController:obj animated:YES];
[obj release];
You don't have any code that is setting the delegate for the UnderRightViewController. I don't know what object owns both of these controllers, but before either UnderRightViewController and FirstTopViewController are displayed it should run code something like this:
FirstTopViewController *ftvc = //... where ever you get a reference to this from
UnderRightViewController *urvc = ...;
urvc.delegate = ftvc;
In your above code you are using custom delegates and also you have used it for sending message to onecontroller class to another controller class. So below is the same sample code of custom delegates, it is working fine in similar way you have to implement and also the problem in your code is you are not setting the delegate, so please follow below how to set the same and call the method. here i have used your same method only return type i have defined as NSString in-spite of void for explaining purpose, but you can use void according to your requirement hope it will be helpful to you:-
First Controller Class AWindowController.h
#interface AWindowController : NSWindowController<sampleDelegate>
{
NSString *textA;
}
#property(readwrite,retain)NSString *textA;
-(IBAction)doSet:(id)sender;
#end
#import "AWindowController.h"
#import "BWindowController.h"
#interface AWindowController ()
#end
#implementation AWindowController
#synthesize textA;
- (id)initWithWindow:(NSWindow *)window
{
self = [super initWithWindow:window];
if (self) {
// Initialization code here.
}
return self;
}
- (NSString *)setTotalViewController:(BWindowController*)controller didTotalChange:(NSString*)total
{
NSLog(#"recieved");
return #"recieved";
}
- (void)windowDidLoad
{
[super windowDidLoad];
// Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
}
-(NSString*)windowNibName
{
return #"AWindowController";
}
-(IBAction)doSet:(id)sender
{
[self setTextA:#"Awindow Button Pressed"];
BWindowController *b=[[BWindowController alloc]init];
b.delegate=self;
[b showWindow:self];
}
#end
Second Controller Class BWindowController.h
#import <Cocoa/Cocoa.h>
#import "sampleDelegate.h"
#class BWindowController;
#protocol sampleDelegate <NSObject>
#required
//-(NSString *)getDataValue;
- (NSString *)setTotalViewController:(BWindowController*)controller didTotalChange:(NSString*)total;
#end
#interface BWindowController : NSWindowController<sampleDelegate>
{
NSString *bTextValue;
id<sampleDelegate>delegate;
}
#property(readwrite,retain)NSString *bTextValue;
#property(readwrite,assign)id<sampleDelegate>delegate;
#end
#import "BWindowController.h"
#interface BWindowController ()
#end
#implementation BWindowController
#synthesize bTextValue,delegate;
- (id)initWithWindow:(NSWindow *)window
{
self = [super initWithWindow:window];
if (self) {
// Initialization code here.
}
return self;
}
- (NSString *)setTotalViewController:(BWindowController*)controller didTotalChange:(NSString*)total;
{
return nil;
}
- (void)windowDidLoad
{
NSString *str= [[self delegate]setTotalViewController:self didTotalChange:#"recieved"];
self.bTextValue=str;
[super windowDidLoad];
// Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
}
-(NSString*)windowNibName
{
return #"BWindowController";
}
#end
Attached screen shot in Output:-
Below is window is the AwindowController.h class
Below in the same above window pressing the button and when Awindow button pressed data will send
and notification will be recieved in Bwindow using above define custom delegates as attached in the screen shot.

Delegates in iOS

I am a newbie to iOS world, so please ignore the obvious.
I am pushing a viewController(HelpViewController) on top of another viewController(MainViewController). When a particular action happens in the HelpViewController, I would like to update a variable inside the MainViewController. I understand for this I need to use delegate.
Here is my delegate header...
#protocol ViewControllerDelegate <NSObject>
#required
- (void) switchToggled:(BOOL)status;
#end
// Protocol Definition ends here
#interface ViewDelegate : NSObject
{
// Delegate to respond back
id <ViewControllerDelegate> _delegate;
}
#property (nonatomic,strong) id delegate;
-(void)sendMessage:(BOOL)status; // Instance method
#end
and implementation...
#implementation ViewDelegate
#synthesize delegate;
-(id)init {
self = [super init];
return self;
}
-(void)sendMessage:(BOOL)status
{
[delegate switchToggled:status];
}
- (void)dealloc
{
[super dealloc];
}
#end
So Now If I want to implement Protocol ViewControllerDelegate I need to specify in MainViewController, which I do as follows --
MainViewController <ViewControllerDelegate>
and
#pragma mark - ViewControllerDelegate delegate
-(void)switchToggled:(BOOL)status{
NSLog(#"Switch Toggled(%d) Message passed to MainViewController",status);
}
My question is how do I specify Object, which delegate property needs to point to, so that it can come back to MainViewController's "switchToggled".
One way I do is by having property inside HelpViewController as follows -
MainViewController.m
HelpViewController *helpVC = [[HelpViewController alloc] init];
helpVC.mainView = self;
[self.navigationController pushViewController:helpVC animated:YES];
[helpVC release];
HelpViewController.h
#property (nonatomic) MainViewController *mainView;
HelpViewController.m
#synthesize mainView;
ViewDelegate *myDelegate = [[ViewDelegate alloc] init];
// assign delegate
myDelegate.delegate = mainView;
[myDelegate sendMessage];
[myDelegate release];
Is this correct way to implement or there is better way to achieve this or am I totally wrong.
Thanks
You should do:
// HelpViewController.h
#protocol HelpDelegate
- (void)switchToggled:(BOOL)status;
#end
// HelpViewController.m
#interface HelpViewController : UIViewController
#property (nonatomic, assign) id<HelpDelegate> delegate;
- (id)initWithDelegate:(id<HelpDelegate>)delegate
#end
#implementation HelpViewController
- (id)initWithDelegate:(id<HelpDelegate>)delegate
{
if (self = [super init])
{
self.delegate = delegate;
}
}
- (void)sendMessage:(BOOL)status
{
[self.delegate switchToggled:status];
}
// MainViewController.h
#import "HelpViewController.h"
#interface MainViewController.h : UIViewController <HelpDelegate>
// MainViewController.m
- (void)someMethod
{
HelpViewController* viewController;
viewController = [HelpViewController alloc] initWithDelegate:self];
...
}
#pragma mark - Help Delegate
- (void)switchToggled:(BOOL)status
{
...
}
Give the delegate a name that makes clear to which class it belongs.
You don't need the extra class/files for ViewDelegate/ViewControllerDelegate. Just define the delegate in header of class it belongs to: HelpViewController.n in this case.
Similar: Implement the delegate method switchToggled: in the real class MainViewController, and not in the extra/unnecessary class ViewDelegate.
The purpose of delegates is to avoid class dependencies. By including MainViewController in HelpViewController you create such a dependency. This is not necessary as I show, and is wrong design.
You were also creating a circular dependency, because MainViewController already needed HelpViewController in order to show it, and now they need each other the other way around for sending the event.
Alternatively you can make HelpViewController's delegate public, have an init without argument, and expect users to set it with helpViewController.delegate = self; or something. But this would only make sense when the delegate being set is optional (which don't seems the case here, so adding it to the init method is appropriate).
I tell you what I would have done:
1) the protocol definition is ok, but do NOT create the class ViewDelegate, so:
//ViewControllerDelegate.h
#protocol ViewControllerDelegate <NSObject>
#required
- (void) switchToggled:(BOOL)status;
#end
2) Your implementation of the delegate method in MainViewController is ok.
3) Now... the important point:
//interface
#interface HelpViewController : UIViewController //or whatever superclass..
{
id <ViewControllerDelegate> _delegate;
}
#property (nonatomic,strong) id<ViewControllerDelegate> delegate;
#end
//implementation
#implementation HelpViewController
- (void)someMethodWhichCallsTheDelegate
{
//do something
...
// call delegate
//if switchToggled: were optional then add the following
//if ([self.delegate respondToSelector:#selector(switchToggled:)]) {
[self.delegate switchToggled:status];
}
#end
4) Now you have to assign the delegate:
//MainViewController.m
HelpViewController *helpVC = [[HelpViewController alloc] init];
helpVC.delegate = self;
[self.navigationController pushViewController:helpVC animated:YES];
[helpVC release];
And that's it!
BTW: if this delegate is related only to HelpViewControllerthen add the protocol definition where you define the interface of the class, it is not necessary to create a separate header file. If instead the protocol is "global", then it can have some sense to declare it separately.

Protocol method does not get invoked, shows delegate 'nil'

I'm working on an iPad App and i'm having issue with delegate... the protocol method does not get invoked. i'm not sure what i'm missing, here is my code.
#protocol pickerLabelProtocol <NSObject>
- (void)selectedPickerData:(UILabel *)sender;
#end
#interface showPickerVC : UIViewController
#property (nonatomic, strong) id <pickerLabelProtocol> delegate;
#end
#implementation showPickerVC
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
//i used breakpoint, the 'delegate' is always nil for some reason?
[self.delegate selectedPickerData:self.mainLabel];
}
----------------------
#interface someViewController : UIViewController <pickerLabelProtocol>
#property (nonatomic, strong) showPickerVC *showPicker;
#end
#implementation someViewController
- (void)selectedPickerData:(UILabel *)sender
{
//protocol method
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.showPicker = [[showPickerVC alloc]init];
self.showPicker.delegate = self;
}
I can not got any mistake From your code but i suggest you that Be clear about when you create object of showPickerVC add it's delegate self
Such Like ,
showPickerVC *obj = [[showPickerVC alloc] init];
obj.delegate = self; /// YOur protocol delegate
.
.
[self presentModalViewController:obj animated:YES];
And Also add code as following
#implementation showPickerVC
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
if([self.delegate respondsToSelector:#selector(selectedPickerData:)])
{
[self.delegate selectedPickerData:self.mainLabel];
}
}
For More information about How to create/use of Protocol.

#protocol on IOS parsing data 2 way?

I have login Code like this :
#protocol LoginDelegate
-(void)DUsername:(NSString *) username DPassword:(NSString *) password;
#end
#interface loginipad : UIViewController {
id<LoginDelegate> delegate;
IBOutlet UITextField *edusername;
IBOutlet UITextField *edpassword;
}
and then i use this object on mainViewController like this :
#interface mainViewController : UIViewController<LoginDelegate> {
and call this methode on mainViewController
-(void)DUsername:(NSString *) username DPassword:(NSString *) password{
userlogin=[username retain];
passlogin=[password retain];
if (!scm.isRunning) {
[scm connectToHost:#"localhost" onPort:8080];
}
}
This method is success to parsing data from login modalview to mainViewController, but i want show progress of process or any message from mainViewController to login modal view when login button is klick (i try MBPrgoressHUD but no success due i use this login on modal view).
My Question how i can parsing data from mainViewController to This login modalview ?
Thanks,
for call the method :
loginipad *plogin = [[loginipad alloc] initWithNibName:#"loginipad" bundle:nil];
plogin.delegate = self;
UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:plogin];
plogin.title=#"Login";
[self presentModalViewController:nc animated:YES];
[nc release];
nc = nil;
[plogin release];
plogin = nil;
answer completely edited
Your question leads to multiple solutions and strategies.
First: general posibilities to implement bidirectional data-transfer between two classes.
via multiple protocols: loose cupling but leads to import-loops which are annoying. I know ho to solve import loops for class-definitions (#class) but I dont know how to solve this for protocols
A.h:
#import "B.h"
#protocol ADelegate
-(void) adelegate:(NSString*)data;
#end
#interface A : NSObject<BDelegate>
{
id<ADelegate> delegate;
}
#end
B.h:
#import "A.h"
#protocol BDelegate
-(void) bdelegate:(NSString*)data;
#end
#interface B : NSObject<ADelegate>
{
id<BDelegate> delegate;
}
#end
via a single protocol: dense cupling :( but no import-loop (this is a working ugly style)
A.h:
//no import here needed
#protocol ADelegate
-(void) adelegate:(NSString*)data;
#end
#interface A : NSObject<BDelegate>
{
id<ADelegate> delegate;
}
#end
B.h:
#import "A.h"
#interface B : NSObject<ADelegate>
{
A* delegate;
}
#end
via pipe/stream: bidirectional data-transfer should by done using a pipe (unbuffered) or stream (buffered)
here I show you a small and simple delegate-pipe but there also exists a NSPipe/NSStream
DelegatePipe.h
#protocol DelegatePipeDelegate
- dataArrived:(NSString*)data;
#end
#interface DelegatePipe : NSObject {
NSMutableArray *delegates;
}
-(void)open:(id<DelegatePipeDelegate>)d;
-(void)close:(id<DelegatePipeDelegate>)d;
-(void)send:(NSString*)data;
#end
DelegatePipe.m
#implementation DelegatePipe
-(id)init
{
if(self = [super init])
{
delegates = [NSMutableArray array];
}
return self;
}
-(void) dealloc
{
[delegates release];
delegates = nil;
}
-(void) open:(id <DelegatePipeDelegate>)d
{
#synchronized(self)
{
if([delegates containsObject:d])
return;
//if([delegates count]>=2) //Pipe contains originally only 2 delegates. but a broadcaster is also nice ;)
// return;
[delegates addObject:d];
}
}
-(void) close:(id <DelegatePipeDelegate>)d
{
#synchronized(self)
{
[delegates removeObject:d];
}
}
-(void) send:(NSString *)data
{
#synchronized(self)
{
for(id<DelegatePipeDelegate> d in delegates)
[d dataArrived:data];
}
}
#end
Second: KVO
KVO is often used in a ModelViewController (MVC) Pattern. eg: visualize data in a view. The network-connection-state in your case is part of data and your loginipad is a view (and a controller)
Authentificator.h
typedef enum eAuthState
{
NOT_CONNECTED = 0,
LOGIN_FAILED,
CONNECING,
CONNECTED
} AuthState;
#interface Authentificator : NSObject {
AuthState state;
}
#property (nonatomic, assign) AuthState state;
#end
Authentificator.m
...
-(void) doAuthWithUsername:(NSString*)name password:(NSString*)pw
{
self.state = CONNECING;
//do network-stuff
}
//delegate from network. here NSURLConnection
-(void) connectionDidFinishLoading:(NSURLConnection *)connection
{
//parse network-answer
BOOL success = YES;
if(success)
self.state = CONNECTED;
else
self.state = LOGIN_FAILED;
}
loginipad.h
#interface loginipad : UIViewController
{
Authentificator *auth;
}
#property (nonatomic, retain) Authentificator *auth;
#end
loginipad.m
#implementation loginipad
#synthesize auth;
//override setter for more comfortable use (add/removeObserver)
-(void) setAuth:(Authentificator *)a
{
#synchronized(auth)
{
[auth removeObserver:self forKeyPath:#"state"];
[auth release];
auth = a;
[auth retain];
[auth addObserver:self forKeyPath:#"state" options:0 context:nil];
}
}
-(IBAction) buttonClicked:(id)aSender
{
self.auth = [Authentificator sharedAuthentificator];
}
-(void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if(![object isKindOfClass:Authentificator.class])
return;
AuthState state = ((Authentificator*)object).state;
NSLog(#"curState: %i",state);
//do sth with state
}
- (void)dealloc {
self.auth = nil;
[super dealloc];
}

How to use protocol instead of delegate in iPhone

Scenario: Need to execute CustomWebview delegate on view controller.
Please help me with this code. Instead of using callback, I need to use "Protocol". Can it be done or we can only use callback in this scenario.
On ViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
//MyWebView *webView = [[MyWebView alloc] initWithDelegate:self callback:#selector(finishLoading)];
MyWebView *webView= [[MyWebView alloc] initWithFrame:CGRectMake(0,0,320, 460)];
[webView LoadURL:#"http://192.168.5.165/"];
[webView setDelegate:self];
[webView setCallback:#selector(finishLoading)];
[self.view addSubview:webView] ;
}
- (void) finishLoading
{
NSLog(#"Finish");
}
On MyWebView.h
#interface MyWebView : UIView<UIWebViewDelegate> {
NSString *strURL;
}
#property(nonatomic, retain) NSString *strURL;
#property (nonatomic, assign) id delegate;
#property (nonatomic, assign) SEL callback;
-(void) LoadURL:(NSString*)url;
#end
On MyWebView.m
#import "MyWebView.h"
#implementation MyWebView
#synthesize strURL,delegate,callback;
UIWebView *webView;
-(id) initWithFrame:(CGRect)frame
{
if(self =[super initWithFrame:frame])
{
webView = [[UIWebView alloc] initWithFrame:frame];
webView.delegate = self;
[self addSubview:webView];
}
return self;
}
-(void) LoadURL:(NSString*)url
{
NSURL *u = [NSURL URLWithString:url];
NSURLRequest *req= [NSURLRequest requestWithURL:u];
[webView loadRequest:req];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
[delegate performSelector:callback];
}
Your question is a bit unclear. A protocol and a delegate are two entirely separate, though related, things--apples and oranges. A protocol defines a list of methods an object may or must respond to:
#protocol Document
+ (id)documentWithContentsOfURL: (NSURL *)aURL;
- (void)writeToURL: (NSURL *)aURL error: (NSError **)outError;
#end
A delegate is an object, usually an instance of a custom class, that is handed to another object for custom processing or feedback--that latter object delegates work to the delegate object.
Are you asking how to convert a delegate category on NSObject to a delegate protocol? (The former used to be Apple's pattern for defining the obligations and abilities of a delegate; the latter is the newer way to do the same thing.) If so, it generally looks something like this:
Delegate Category on NSObject
#interface NSObject (WidgetDelegate)
- (void)doSomethingWithWidget: (Widget *)w;
#end
#interface Widget : NSObject
#property (readwrite, assign) id delegate;
#end
Delegate Protocol
#protocol WidgetDelegate <NSObject>
- (void)doSomethingWithWidget: (Widget *)w;
#end
#interface Widget : NSObject
#property (readwrite, assign) id <WidgetDelegate> delegate;
#end
Is that what you're looking for? If not, can you clarify exactly what you're trying to do?
Also see Apple's Communicating with Objects, which discusses delegates, protocols, and selectors. Though its listed under Mac OS X, most (if not all) appears to apply to iOS also.
On ViewController.m
#interface MyViewController : UIViewController<MyFinishLoadingDelegate> {
//your own definition
}
- (void)viewDidLoad
{
[super viewDidLoad];
//MyWebView *webView = [[MyWebView alloc] initWithDelegate:self callback:#selector(finishLoading)];
MyWebView *webView= [[MyWebView alloc] initWithFrame:CGRectMake(0,0,320, 460)];
[webView LoadURL:#"http://192.168.5.165/"];
[webView setDelegate:self];
[self.view addSubview:webView] ;
}
- (void)finishLoading //this is your implementation for MyFinishLoadingDelegate
{
NSLog(#"Finish");
}
On MyWebView.h
//you declare the protocol here to tell anyone who'd like to act like your delegate that they need to implement "finishLoading"
#protocol MyFinishLoadingDelegate <NSObject>
- (void)finishLoading;
#end
#interface MyWebView : UIView<UIWebViewDelegate> {
NSString *strURL;
}
#property(nonatomic, retain) NSString *strURL;
#property (nonatomic, assign) id<MyFinishLoadingDelegate> delegate;
-(void) LoadURL:(NSString*)url;
#end
On MyWebView.m
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
[delegate finishLoading];
}