• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: NSSound
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: NSSound


  • Subject: Re: NSSound
  • From: Sherm Pendley <email@hidden>
  • Date: Thu, 7 Nov 2002 17:55:11 -0500

On Wednesday, November 6, 2002, at 09:32 PM, Steve Mills wrote:

This works:

NSSound* snd = [NSSound alloc];

[snd retain];
[snd initWithContentsOfFile: fileName byReference: NO];
[snd play];

This should be:

NSSound *snd = [[NSSound alloc] initWithContentsOfFile: fileName byReference: NO];
[snd play];

But this doesn't:

NSMutableData* data = [[NSMutableData dataWithContentsOfFile: fileName] retain];
NSSound* snd = [[NSSound alloc] retain];

[snd initWithData: data];
[snd play];

And this should be:

NSMutableData *data = [NSMutableData dataWithContentsOfFile: fileName];
NSSound *snd [[NSSound alloc] initWithData: data];
[snd play];

The first [snd play] returns YES but the second returns NO. If it's the same data, why does only the first method work? I even tried naming the sound in the second method.

Note that in neither of the above corrections is snd retained - an object obtained with init is not autoreleased, and so doesn't need to be retained. Neither is data; unless you need to keep it to initialize other sounds at some future point, it doesn't need to be retained.

That's not the cause of the problem, though - excessive retains don't cause bugs, they simply cause your program to leak memory.

The problem is that you're calling retain too early, before the snd object is initialized with init. That may not return anything useful. In the first example, you're simply sending snd a retain message, so no harm is done - other than possibly excessive memory usage. In the second example, though, you're storing the result of the retain call, which may be nil, in snd. A message sent to nil will always return nil, or zero, which in the context of a BOOL type is NO.

To learn more about memory management in Objective-C/Cocoa, check out: <URL: file:///Developer/Documentation/Cocoa/TasksAndConcepts/ProgrammingTopics/MemoryMgmt/
index.html>

sherm--

If you listen to a UNIX shell, can you hear the C?
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives: http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.

References: 
 >NSSound (From: Steve Mills <email@hidden>)

  • Prev by Date: Re: Getting thumbnail of document to appear?
  • Next by Date: [OT] Re: To all cocoa developers - new cocoa dev forum
  • Previous by thread: Re: NSSound
  • Next by thread: Re: NSSound
  • Index(es):
    • Date
    • Thread