在@implementation中使用'self'

Gar*_*ett 3 objective-c ios trigger.io

我试图播放语音音频之上iPodMusicPlayer通过使TriggerIO本地插件,不过我无法访问self对象.

#import "alert_API.h"

@implementation alert_API

+ (void)play:(ForgeTask*)task text:(NSString *)filename {
    NSURL* url = [[NSBundle mainBundle] URLForResource:@"Rondo_Alla_Turka_Short" withExtension:@"aiff"];
    NSAssert(url, @"URL is valid.");
    NSError* error = nil;


    /* ERROR: /Users/gsquare567/forge-workspace/plugins/audio/inspector/ios-inspector/ForgeModule/alert/alert_API.m:45:13: Member reference type 'struct objc_class *' is a pointer; maybe you meant to use '->'? */
    self->player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];

    /* ERROR: /Users/gsquare567/forge-workspace/plugins/audio/inspector/ios-inspector/ForgeModule/alert/alert_API.m:45:13: Incomplete definition of type 'struct objc_class' */
    if(!self.player)
    {
        NSLog(@"Error creating player: %@", error);
    }


    [task success:nil];
}

@end
Run Code Online (Sandbox Code Playgroud)

该属性定义alert_API.h如下:

#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>

@interface alert_API : NSObject

@property (nonatomic, strong) AVAudioPlayer* player;
+ (void)play:(ForgeTask*)task text:(NSString *)filename;

@end
Run Code Online (Sandbox Code Playgroud)

我需要做什么才能player在我的API中访问该属性?

谢谢!

Mik*_*ler 6

您的play:text:方法是静态的,意思self是不引用具有该属性的实例,而是引用类对象alert_API.您可以将方法更改为实例方法(- (void)而不是+ (void)):

- (void)play:(ForgeTask*)task text:(NSString *)filename;
Run Code Online (Sandbox Code Playgroud)

或者,如果要保持方法静态,则必须实现一个返回播放器单例的静态方法:

+ (AVAudioPlayer *)playerInstance;
Run Code Online (Sandbox Code Playgroud)

然后使用[alert_API playerInstance]从您的方法访问播放器.

  • `+`表示类方法,而不是静态方法. (5认同)
  • @rmaddy +1也"自我在这种情况下无效.它是有效的.它是对类对象的引用,而不是类的实例. (4认同)