asterix22
asterix22

Reputation: 53

Method returns my object objective c

I have a class named myClass that contains 3 NSInteger and I can't do a method like that:

- (myClass)getClass {
    myClass *class1;
    return class1
}

it gives me an error

EDIT: the error is in the .h

- (myClass *)getClass; Error: expected ')' before 'myClass'

Upvotes: 1

Views: 1473

Answers (3)

user142019
user142019

Reputation:

I suppose you want to return an instance of myClass. You can do that like this:

- (myClass *)getClass {
  myClass *class1 = [[[myClass alloc] init] autorelease];
  return class1;
}

If instead you want to return the class itself:

- (Class)getClass {
  return myClass;
}

You can change the - to a + if you want it to be a class method instead of an instance method. Your question wasn't quite clear.


In Objective-C you can never return an object by value, since the size of an object in Objective-C isn't known at compile time. If you don't like the asterisks everywhere you can do typedef myClass* myClassRef and return a myClassRef instead.

Upvotes: 2

elp
elp

Reputation: 8131

Completing Mahesh response, you need do:

- (myClass*) getClass { 
   myClass *class1; 
   return class1; 
}

or if method is static, you need do:

+ (myClass*) getClass { 
   myClass *class1; 
   return class1; 
}

Upvotes: 0

Mahesh
Mahesh

Reputation: 34625

In Objective-C, every class type is a reference type. So, the return type should be myClass*. When we have a pointer like -

int *ptr = new int; // The type of ptr is int* but not int. Same is the case for 
                        // class types too.

Upvotes: 0

Related Questions