Play NSSound in NSObject (Mac Application with Objective-C)

I am making a game in which I need to play music. To make my code more manageable, I wanted to create an NSObject that takes care of sounds (like attenuation, playing sounds in a playlist, etc.). I have this code:

NSSound *music = [[NSSound alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:self.filename ofType:self.fileExtention] byReference:NO];
[music play];

This code works when I put it in the AppDelegate.m file, but it doesn't work when I put it in a new NSObject class.

Code in the NSObject class (named Music):

- (void)playMusic:(NSString *)fileName ofType:(NSString *)type
{
    NSSound *music = [[NSSound alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:self.filename ofType:self.fileExtention] byReference:NO];
    [music play];

    NSLog(@"Works!");
}

I call a method with this code in AppDelegate.m:

[[[Music alloc] init] playMusic:self.fileName ofType:self.extension];

When this is done, he writes the "Works!" Log. which means the code is executed.

, AppDelegate, NSObject. - , NSSound NSObject ( , ?), , , ? ;)

+6
1

,

dispatch_async(dispatch_get_main_queue(), ^{
  // do work here
});
+1

All Articles