3

I am new to Objective C and am trying out some basic concepts but hitting a few brick walls

Essentially what I am trying to do is write a class that returns an array when messaged from another class

The class that returns the value would be something like -

ReturnClass.h

#import <Foundation/Foundation.h>

@interface ReturnClass : NSObject {

}


-(NSMutableArray *) getLocation ;


@end

ReturnClass.m

    #import "ReturnClass.h"

    @implementation ReturnClass

    -(NSMutableArray *) getLocation {
   //do some stuff to populate array
    //return it
        return  latLngArray;
    }
    @end

I then wanted to call this in to another implementation in order to harvest the value

SomeOtherClass.m

#import "ViewController.h"
#import "ReturnClass.h"

@interface ViewController ()

@end
@implementation ViewController
- (void)viewDidLoad
{
    [super viewDidLoad];
NSMutableArray *latLngArray = [[getLocation alloc] init];
}

I appreciate there is probably a fair bit wrong with this but please be gentle as I am trying to learn :)

user499846
  • 681
  • 3
  • 11
  • 24

3 Answers3

4

The call would looke like this:

- (void)viewDidLoad
{
    [super viewDidLoad];
    ReturnClass *retClass = [[ReturnClass alloc] init];
    NSMutableArray *latLngArray = [retClass getLocation];
}

This would give you the array produced by getLocation.

This code makes a new instance of ReturnClass every time it needs the array; this may or may not be what you want, because you cannot keep any state between invocations. If keeping state in ReturnClass is what you need, you would have to implement a singleton (here is a link to a question explaining a very good way of implementing singletons in Objective C).

Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

You should review your concepts of object oriented programming in general. In particular, do not confuse a class with a method.

In your code, you have to instantiate a ReturnClass instance first to be able to call its method getLocation.

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
ilmiacs
  • 2,566
  • 15
  • 20
0
NSMutableArray *latLngArray = [[getLocation alloc] init];

For starters, this line misses the mark. You're sending +alloc to the name of a method. You should be sending that message to a class, like this:

ReturnClass *myObject = [[ReturnClass alloc] init];

and then sending messages to the resulting object, like this:

NSMutableArray *latLngArray = [myObject getLocation];
Caleb
  • 124,013
  • 19
  • 183
  • 272