开发者

Objective C: Include class and call method

开发者 https://www.devze.com 2022-12-28 17:30 出处:网络
I have built a class which has a few methods in it, once of which returns an array, lets call this class A.

I have built a class which has a few methods in it, once of which returns an array, lets call this class A.

I have a second class, class B, which I would like to u开发者_开发知识库se to call the method from class A.

But, now how do I call that method from class A and store what is returned in a var in class B? Do I have to initiate the class? I have made sure to include the .h file from class A into class B.

Thanks for helping a newbie.

UPDATE:

Here is how I thought I could do this (DataStore is my class A and pushRideData is my method that returns an array):

DataStore *store = [[DataStore alloc] init];
trailsArray = [store pushRideData];


Assuming you have files A.h, A.m B.h and B.m to define your two classes, then you need to do the following:

  1. Make sure A.h and B.h are #imported into your projects PCH file (this is the easiest/fastest way, but you could also choose to import the files into all the .m files, instead).

  2. If you refer to a class -- say, B *something in A.h -- before that class's header file is imported, then use a forward class declaration to shut up the compiler. I.e. @class B; before the @interface A:NSObject in A.h

  3. If you want to call an instance method of a class, you need to instantiate the class as you describe. Or, if the instance is created somewhere else, you'll need some mechanism to retrieve it. A class method, perhaps, or a global variable or a controller or something like it.

None of this is really that much different than straight C save for a formal notion of Objects (as opposed to malloc'ing a bunch of memory and passing around pointers).


That's a fairly abstract question. Yes, you need an instance to be able to store instance variables in it. You will need to allocate and init the instance, assinging it to an instance or local (pointer) variable in the calling class unless it is one of the several in the Cocoa Touch frameworks which use the singleton pattern, such as the application delegate. Such singletons have special case-specific class methods for obtaining the singleton instance.

0

精彩评论

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

关注公众号