Hristo
Hristo

Reputation: 6540

Moving functions to separate classes

I have been building an iOS app and one of my ViewControllers had become full of functions like:

CGPoint randomPoint()
{
  //Code goes here
}

I now want to move them to class A (or protocol, I am not sure what will work for me), import it in the VC and call the just like before:

p=randomPoint(); //NOT A.randomPoint(), [A randomPoint] or whatever

I tried using the C++ class template, but it has problems with CGPoint, CGRect and so long.

How can I accomplish that?

Upvotes: 1

Views: 479

Answers (2)

Pedro Mancheno
Pedro Mancheno

Reputation: 5237

If you are wondering were to put C functions like the one you are describing, the best practice is to move them into a separate .h file that has a meaningful name. For instance MyGeometry.h

Make sure you give a descriptive name to your function, such as:

static inline CGPoint CGPointMakeRandom() {
    // your code
    return point;
}

Upvotes: 3

AdamG
AdamG

Reputation: 3718

You could make a separate objective c class with class methods.

In the header file declare the method like this (let's say you want to call it

#import <UIKit/UIKit.h>

@interface pointHelper : UIViewController

     +(CGPoint) randomPoint;

And then in the .m file

 @implementation pointHelper
     +(CGPoint) randomPoint{
         //// implementation
     }

When you want to evoke the method in another file.

#import "pointerHelper.h"

You will then be able to access the method like this...

CGPoint thePoint = [pointHelper randomPoint];

Or if you had an object of the class..

CGPoint thePoint = [[pointHelperObject class] randomPoint];

This is a better way of doing it, since it makes your code much clearer. [pointHelper randomPoint] tells you why you are evoking the method and what it is doing. You are using a class that has utilities for points, and you are using it to grab a random point. You don't need an object to evoke this method, because it is controlled abstractly by the class. Just be careful not to try to access properties of the class within the class method.

Upvotes: 0

Related Questions