开发者

iPhone best location for code used by more than one viewcontroller?

The more I develop iPhone apps, the more reusable functions I write. At the moment I just copy them into the .m files that need them. But would it be better to have a separate .m file and #import it instead? I don't wish to compile a library, I just want to know how other folks have handled this. Thanks.

Clarification: I want other .m files to obtain the external code in such a way that they think it is their own. The selectors and t开发者_开发知识库he variables are recognized just as if they were in the target .m file rather than having been injected in some fashion.

Do I put the shared code in both a .m and a .h file? Do I use #import? I don't want the shared code to be regarded as its own class, needing instantiation.


I don't know what kind of methods you are talking about but when adding functionality to for example most UIViewControllers then you should be writing categories to existing classes. We for example have category for UIImage that allow us for any UIImage add rounded corners.

+ (UIImage *)imageWithCornerRadius:(UIImage*)img cornerRadius:(int) cornerRadius {}

or with UIColor category we have extension methods like [UIColor darkBrandColor]

A category looks very simple:

#import "ClassName+CategoryName.h"



@implementation ClassName ( CategoryName )

// method definitions

@end

Later you can simply #import ClassName+CategoryName.h to use the extensions.

Categories in Objective-C


This is a partial answer to my own question. If I create a class for my helper functions and define the methods with a + instead of a -, then they are "static" or "class" methods. I can call them from within another class without having to create an instance of their own class.

Let's say my Class is called MyHelperFunctions, and has the usual MyHelperFunctions.h and MyHelperFunctions.m files. I can declare this method:

   + (int) addOneToThisNumber:(int)MyNum;

And then call it from other classes like so:

   int k = 0;
   int i = [MyHelperFunctions addOneToThisNumber:k];

Of course I need to do this:

   #import "MyHelperFunctions.h"

in the .m file of all classes that want access to those helper functions.

The reason I say this is a partial answer is that I put a bunch of sqlite3 functionality in my helper class file, but when I call that from another class, I get "out of memory" errors or "library routine called out of sequence" errors.

Thus, I seem to have created two problems that didn't exist before: a threading issue as well as a memory issue caused be creating an instance of a database in one class and then passing it to another class to try to open that DB.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜