简体   繁体   English

如何在Objective-C中包含和调用示例代码方法?

[英]How do include and call sample code methods in Objective-C?

iPhone/Mac "play a sound class": link text iPhone / Mac“播放声音类”: 链接文本

I find an awful lot of great objective-c classes and code samples here... and elsewhere. 我在这里和其他地方找到了很多很棒的Objective-C类和代码示例。

I successfully create the .h and .m files, but how do I call them from my existing code? 我成功创建了.h和.m文件,但是如何从现有代码中调用它们?

  • Where do I put the @class or #import statements? 我在哪里放置@class或#import语句?
  • How do I call the methods? 如何调用方法?
  • What if I need to play 2-3 different sounds files? 如果我需要播放2-3种不同的声音文件怎么办?
  • Why include the code... without any info about how to ever use it anywhere? 为什么要包含代码...而又没有关于如何在任何地方使用它的任何信息?

Usually Annette, you can tell what needs to be done by looking at the objects superclass 通常是Annette,您可以通过查看对象超类来判断需要执行的操作

in this case, if you look at the .h file you can see @interface Sound : NSObject 在这种情况下,如果查看.h文件,则可以看到@interface Sound:NSObject

Sound is the name of this Class, NSObject is our superclass 声音是该类的名称,NSObject是我们的超类

the initWithPath method is returning itself and does a [super init] meaning that it calls the parents init method. initWithPath方法将返回自身并执行[super init],这意味着它将调用父级init方法。

In order for you to call this methods theres one of two ways. 为了让您调用此方法,有两种方法之一。

You can have a property that you manage lets say, in your delegate. 您可以在代表中拥有一个可以管理的属性。

@class Sound;
@interface ScanViewController : UIViewController  {
    Sound *aSound;
}
@property (nonatomic, retain) Sound *aSound;

then somwhere in your delegate 然后在你的代表处

- (void) someFunction() {
   aSound = [[Sound alloc] initWithPath:@"pathtoSound"];
}

If you didnt want it to be a property you can easily create a new Sound object anywhere in a .m file like so. 如果您不希望它成为属性,则可以像这样在.m文件中的任何位置轻松创建一个新的Sound对象。

Sound *mySound = [[Sound alloc] initWithPath:@"pathtoSound"];

If you wanted multiple sounds, Store them in a Sound Array 如果您想要多种声音,请将它们存储在声音阵列中

PS dont forget to release these objects since you alloc'ed them. PS不会忘记释放这些对象,因为您已对其进行了分配。

Wherever you want to call a method from one of the classes, put #import "SomeClass.h" at the top of the .h file. 无论您要在其中一个类中调用方法的何处,都将#import "SomeClass.h"放在.h文件的顶部。

Then you can do [SomeClass someMethod] or SomeClass *object = [[SomeClass alloc] init] , or whatever you want to do. 然后,您可以执行[SomeClass someMethod]SomeClass *object = [[SomeClass alloc] init] ,或执行任何操作。

This is pretty basic, you should read through The Objective-C Programming Language Guide 这是非常基础的,您应该通读《 Objective-C编程语言指南》

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM