views:

1522

answers:

2

I'm creating an app in which I do the same thing multiple times. I'm going for as little code as possible and I don't want to repeat myself.

I need the PHP equivalant of a reusable function, where I set an input, and the function will return the output.

The app is a URL shortener, so the input as you may assume is a URL, and the output is the short URL.

What's the best way to go about this? I know I can code the same thing twice, but I hate to repeat myself.

Hopefully I'm getting my point across. Any help is greatly appreciated. -Giles

+1  A: 

Apologies if I'm oversimplifying your question, but are you asking how to define an Objective-C method? If so, you're going to have to learn Objective-C, there's no way around it:

The Objective-C Programming Language - Object Messaging

You can do a lot of great things with no code on the iPhone and Mac platforms, but it's hard to imagine completing any useful application without writing some code.

Example

- (float)multiplyThisFloatByTwoPointFive:(float)numberToMultiply
{
     return numberToMultiply * 2.5;
}

To call it:

[self multiplyThisFloatByTwoPointFive:3.7];

Libraries

If you mean "I want to put these non-class-specific methods somewhere I can access them universally", eg, a library, you can do this in two ways:

  1. Create some sort of "library" class like "MySpecialMathClass" (not to be confused with "my special education math class") or "MyAppAnimationTricks" and put your methods there (you'd define them as +someMethod: not -someMethod:, class- not instance-method, per Objective-C).
  2. If they only ever deal with primitives (such as int, float, double ...), consider just making them C functions, rather than Objective-C methods.
Joshua Nozzi
Well technically there is nothing stopping him from using C functions with objective-c objects, it just seems like it'd generally be frowned upon. I'd probably put it in a singleton class somewhere (app delegate?), or as a static method on a class like you mentioned.
Bryan McLemore
A: 

I am pretty much a newbie at this, but you can certainly write functions (as opposed to methods) in Objective C.

I wrote several utility functions recently. I created an NSObject file to place them in, but it has no ivars or methods declared, just the functions. Then implement the functions in the .m file, and import the .h file into any class file where you want the functions. You can obviously call these from anywhere in any .m file that has imported the function file.

John Doner

John R Doner
Where is the code examples ;( this is just pretty answer for: "Yes, you can."
Daniel T. Magnusson