views:

69

answers:

2

New to iPhone development, not new to software development in general. I want my Objective-C/iPhone source code to look "unsurprising" to someone else reading it.

Wondering what is the accepted practice for code organization within one class?

As an example, I have a view controller like so:

@interface SomeViewController : UIViewController 
    <UIPickerViewDelegate, 
    UIPickerViewDataSource, 
    UITextFieldDelegate> {
}

What is the accepted practice regarding the ordering/placement of the methods for these protocols within the .m file? I know that it doesn't technically matter, but, as I said, I want someone reading my code to be unsurprised at how I've organized it.

As an aside, if implementing these sorts of protocols on my view controllers is considered a bad practice, please let me know in a comment, and I'll ask another question for that (or just point me to an existing one)

A: 

While the Apple sample code is certainly not perfect, it at least is a good model for being "unsurprising" in how you organize your source. Remember, every other iPhone programmer out there will have seen a lot of Apple sample code already, so they'll already be familiar with how it's structured.

bdrister
Can you be more specific, at least WRT to the protocol implementation? I can't seem to find a way to make XCode "implement the protocol" (as can be done in e.g. Java IDEs), so I don't know where it would put the method stubs
davetron5000
+2  A: 

I think the best practice is this :

1/ Put all the methods in the same protocol near each other

2/ Put the #pragma at the top of that block

#pragma mark UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField {
  // some code
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
}

#pragma mark UIPickerViewDelegate

So, when people use XCode to see the list of methods, they will know where to look for a method in a particular protocol:)

vodkhang
That makes sense; so would it be something like @synthesizes, then methods I added to the class, then protocol1, then protocol2, then overridden methods, and finally dealloc??Or how does one #pragma mark the class' methods not part of a protocol?
davetron5000
You can put another #pragma mark Instance's method, #pragma mark Class's method. Usually, this general rule is good enough. It depends on your team convention to go into details. For our team, we put @synthesize, then init, dealloc because they are important, then view, then controller (for UIViewController), then we can divide by functionality
vodkhang
But it depends on the skills of programmers. Maybe your team is strong at memory management and weak at view controller, you can consider putting it at the top because it will be frequently accessed when there is a bug or change
vodkhang