how to fault find if a delegate call is not being picked up in objective-c - iphone

Just implementing my first delegate in objective-C. I thought I had everything in place however the call from my AddController back to ListController isn't being picked up in the ListController.
Given that I'm not getting an exception, and that I can see that the code does get to the point in the AddController where it calls the delegate, are there any fault finding tips?
So for example:
given the "delegate" call (see below) did not throw an exception can I assume that my delegate declarations in the same file are OK?
"[delegate newItemController:self didFinishWithSave:YES];"
given the parent controller so to speak does have the delegate specified in the *.h definition (see below), then this does implied I've correctly implemented the method in the *.m file, noting I get no build errors?
#interface RootViewController : UITableViewController {
is there a known way for delegate calls to go missing without an exception if certain items don't like up (i.e. if there is what should I check for)
thanks

Most common error I've seen for a delegate method not being called is a nil delegate property. In other words, forgetting to specify who the delegate is?
As for debugging tips, anytime I've seen a problem where a delegate is not being called is to set breakpoints throughout the code and step through the code. Then you can see where things are going and what is or isn't being called.
Also, you mention exceptions a lot. Objective C prefers not to use exceptions as they are a relatively expensive call in the language (unlike say Java). Objective C can and does use exceptions but they are rare. You might want to "beaf up" your understanding of error handling in objective c.

Have you set your delegate variable like this in your AddController:
self.delegate = <instance of ListViewController>
If it has not been set, then the delegate would be nil and the method call to the nil would result in nothing. Otherwise, delegate calls wouldn't really go missing like that.
I didn't understand your second point though.

Related

Best way to do init without repeating code?

Each view class has multiple init methods - ones already included as part of UIView, and then additional ones - and each of them set up the same elements in the same way. I therefore usually have them all running a [self initialSetup]; method, which includes the setting up of all of these elements.
The problem i've ran into is that if a subclass also has an initialSetup method, it would override the superclass initialSetup method, and thus the superclass would have to have the method be public in order to still function. This causes problems with organisation, as the method should never be called other than from init, so has no reason to be public.
You've hit upon a problem that there's no perfect fix for. What you'd ideally have is a method that can't be subclassed in the normal sense, that's accessible only to instances of that exact type of class.
Where this is a risk, the normal practice seems to be to incorporate the class name into the setup method. So instead of initialSetup you'd have something like myViewSubclassInitialSetup.
You can also add something like this at the top of your method:
NSAssert([self isMemberOfClass:[ThisClass class]],
#"IniitalSetup called by sub- or superclass")
Then your debug builds will raise an exception if a subclass or superclass ends up calling your init method. That'll give you a place for a breakpoint and a stacktrace that should allow you to find the problem very quickly.
It won't add any code to your release builds.
Change the name of initialSetup to something like initialSetupClassName - subclasses, even if they accidentally used the same pattern, would not use the same name as they had a different class name.
You can also use an "_" prefix for private methods you would rather not be called, but the subclasser may do that also.
It sounds like you are missing a designated initializer. Designate one initializer as the official one that actually performs the setup, and have all the others just call that with some degree of customization. Usually the designated initializer will be the one with the most detail — for example, if you have init, initWithName:, initWithName:age: and initAsFiveYearOldNamed:, the designated initializer will be initWithName:age: and the other initializers would just call that method with the arguments filled in appropriately.
Unfortunatly Objective C doesn't provide a way to achieve that in a "clean" way. The ideal solution would be a protected method. But that's not possible in Objective C
Apple had this problem, when they were creating the UIGestureRecognizer. There were some methods they really didn't want to get called by somebody, but which had to be overwritten by subclasses. The way they chose to deal with this, was to create a seperate header file (UIGestureRecognizerSubclass.h), that contains a category to the original UIGestureRecognizer with those "protected" methods. The additional header is only to be imported by subclasses (i.e. for subclassing purposes). See UIGestureRecognizer Class Reference for some details.
Of course that doesn't prevent anybody from misusing the additional header file, but at least it clearly states your intention and keeps your code well structured. Also you won't be "bothered" by autocompletion for the additional methods, when just using the class.
Personally I only use an additional header, if it is extremely important that nobody calls it directly. In most cases I think it's ok to use public methods and make a note for what it's inteded. The iOS Framework also has many of these cases. F.e. many methods of UIViewController's viewDidLoad etc.

Iphone Error "request for member connectWeb in something not a structure or union"

When I call my urlconnection method from my (IBAction)buttonpressed method like this:
[self connectWeb];
I get error "request for member connectWeb in something not a structure or union"
but when I call the same method from my - (void)viewDidLoad method it works!?
Where is the connectWeb method in your implementation file?
I would guess that it is before viewDidLoad but after buttonPressed.
The reason for this is that the connectWeb method has been declared before viewDidLoad, so viewDidLoad is aware of it, whereas it's after the buttonPressed method, so the buttonPressed method isn't aware of it.
You have a couple of options.
Declare the method before any other method uses it.
- (void)connectWeb;
Then you can implement it anywhere within the implementation.
Move the implementation of connectWeb to before both viewDidLoad and buttonPressed - both the methods will then be aware of connectWeb.
A method missing from the header wouldn't cause this problem. Because Objective-C is dynamic, it will check if the instance implements that method at runtime, so as long as the method exists it will work. You would just get a compiler warning at build time.
Try deleting the line [self connectWeb] from your button delegate method and copy/pasting it from your viewDidLoad (or retyping it). From the error you're getting, it sounds like there might be an extra character in your statement. This happens to me from time to time, because I use synergy to share my keyboard & mouse between multiple computers.

Where is the code behind this method

Yes all, another newbie question!
I'm doing some maintenance work on an app I inherited and I'm trying to find the code behind this method. In my task.h file I have a optional method, doTask, declared in a protocol, TaskDelegate. In my task.m file I located the method definition for doTask, but it refers back to it's method name so I assumed I'd find another "more complete" method definition in another object. WRONG! I'm obviously missing something very basic here. I haven't been able to find any other references in my code to doTask.
Here's the initial declaration in my header file, task.h
#protocol TaskDelegate<NSObject>
#optional
- (void) doTask;
Here's the method definition in my implementation file, task.m
- (void) doTask
{
if ((self.delegate != nil) && ([self.delegate respondsToSelector:#selector(doTask)]))
{
[self.delegate doTask];
}
}
I assume my method definition is first determining if I have a object delegate already in existence and then seeing if it has a doTask method defined within it; if it does, then it's telling it to execute the doTask method on that delegate. Am I correct?
Well, if so, my question becomes where is the code behind doTask which actually does something? I've really got to be missing something basic here. All help is appreciated! Thanks in advance for your assistance...
As middaparka said, your assumption is spot-on. As for finding the function code for the doTask method, do a Edit -> Find -> Find in Project or command + shift + F and enter 'doTask' (or whatever the function name really is) into the search bar and set it to 'In Project' and it will pull up all instances where the function text shows up, including the function definition.
I assume my method definition is first
determining if I have a object
delegate already in existence and then
seeing if it has a doTask method
defined within it; if it does, then
it's telling it to execute the doTask
method on that delegate. Am I correct?
This is precisely what's happening.
In terms of your "where is the code behind doTask" question - it should be in whatever delegate registers itself with the class in question. (It's a bit confusing in that the same method name is being used but the intent behind the [self.delegate doTask]; line should be clear.)

Objective-C: call a method you just created

Simple question, as I am coming from another programming language. In Objective-C, lets say in a controller class I want to separate certain code into its own method, how do I call that method let's say, from viewLoad. As an example, let's say I create a method:
(void)checkIfInputCorrect
{
NSLog(#"text");
}
Now, i wanted to have in a delegate method, call this method. I tried [self checkIfInputCorrect] and get a warning saying Controller may not respond to -CheckIf...
I thought something like checkIfInputCorrect() would work that gives an error as well.
Basically how do you call a method?
Add this to your .h file
- (void)checkIfInputCorrect;
Call it with:
[self checkIfInputCorrect];
You need to list the method in the interface (ideal) or list the method implementation before the calling method (less ideal) so that the compiler can know that the class responds to the selector before it compiles the calling line.
To paraphrase Martin,
In your .m file, make sure your method -checkIfInputCorrect is placed so that it's physically above the method that has the line: [self checkIfInputCorrect];

Call back style

I am writing an iPhone application which in numerous places needs to perform non HTTP or FTP networking of a very simple request response type.
I've wrapped all this up into a SimpleQuery class that integrates with the run loop.
SimpleQuery *lookup = [[SimpleQuery alloc] init];
[lookup setDelegate:self];
[lookup doQueryToHost:queryServer port:queryPort query:queryString ];
As you can see the calling object sets itself as a delegate. When the results are complete it then calls a method on the delegate with the results.
[delegate simpleQueryResult:resultString simpleQuery:self];
I am now in a position where I have a user of SimpleQuery that has two types of query so I need to extend SimpleQuery to support this.
I can think of two sensible ways of doing this.
Firstly passing a selector into doQueryString, or a seperate doQueryStringWithSelector.
[lookup doQueryToHost:queryServer port:queryPort query:queryString selector:#SEL ];
Secondly passing a tag into doQueryString so that when the delegate is called it can query the tag, as the simpleQuery is passed, to find out what the results are for.
[lookup doQueryToHost:queryServer port:queryPort query:queryString withTag:tag ];
I'm just wondering which is best from a coding style perspective, the first seems simpler but tagging seems more in keeping with the iPhone SDK and Interface Builder
An option which is used commonly in Apple's code (for example, in UIControl) is to provide both a target object and a selector. This works only if there is a single callback, and is more appropriate than a delegate in that case. (If there are multiple callbacks, then you'll probably have to go with a delegate and the tag approach.)
If you go this route, then you do away with the delegate altogether and instead have a method with a signature like this:
doQueryToHost:(id)queryServer port:(int)queryPort query:(NSString*)queryString target:(id)target action:(SEL)action
Note that "action" is typically preferred over "selector" in methods arguments in this case. The query would simply call the selector on the target when done. This would allow your clients to have multiple selectors, and also multiple target objects; this can help clean up code because you don't need to shove everything into a single delegate object.
If you want to go with your tag route, you should call it "context", which is what Apple uses (for example, in addObserver:forKeyPath:options:context).
There's a third option that's a common pattern in the kits, which is to use #protocols.
For example:
#protocol QueryCompleteHandlerProtocol
- (void)queryType1Complete:(int)intStuff;
- (void)queryType2Complete:(float)floatStuff;
#end
What this does is declare a set of method calls that an object adopting the protocol has to conform to (the compiler will actually enforce this).
So your SimpleQuery object will hold on to something like the delegate pointer, which you might declare like this among the ivars:
NSObject<QueryCompleteHandlerProtocol> *callback;
What this tells the compiler is that callback is an object that descends from NSObject and adopts the QueryCompleteHandlerProtocol protocol. Sometimes you see this written as:
id<QueryCompleteHandlerProtocol> callback;
When you want to call the callback there's nothing special about them, SimpleQuery's methods will just call:
[callback queryType1Complete:1];
[callback queryType2Complete:2.0];
Finally you client for the procotol class will declare itself as adopting the protocol:
#interface MyClass : NSObject<QueryCompleteHandlerProtocol>
...
#end
And will set itself as the callback with some code like:
[lookup setCallback:self];
This is where the compiler checks that MyClass conforms to QueryCompleteHandlerProtocol, meaning it has implemented queryType1Complete: and queryType2Complete:.
I'm not sure I understand the problem here. Can't SimpleQuery's user just set another delegate object for the second query, or branch on the simpleQuery: parameter? That's a basic part of the delegate pattern, just like having two UIActionSheets for one view controller.