01.02.2014 Views

Objective-C Fundamentals

Objective-C Fundamentals

Objective-C Fundamentals

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Memory zones<br />

191<br />

Memory zones have additional advantages<br />

Although not a consideration for the iPhone and iPad, which don’t implement paging<br />

to a secondary storage mechanism (such as disk) in their virtual memory implementations,<br />

another use of custom memory zones is to ensure the locality of related data.<br />

Custom memory zones are commonly used in audio buffer or streaming-related code,<br />

for example, because they help prevent performance impacts caused by swapping<br />

buffers in and out of disk-based storage if two commonly used buffers happen to be<br />

allocated on different memory pages.<br />

The first argument to NSCreateZone specifies how much memory to initially reserve<br />

for the pool, and the second argument specifies the granularity of future memory<br />

allocations for the pool. In this example, 2 megabytes of memory are preallocated for<br />

use by the pool; if all of this memory is eventually consumed, a request to allocate one<br />

additional byte will expand the memory zone by a further 1 megabyte. This helps<br />

reduce fragmentation and helps ensure the locality of different objects allocated from<br />

the same zone.<br />

Once a memory zone is created, you can allocate a new object using memory from<br />

the zone by sending an allocWithZone: message:<br />

NSString *myString = [[NSString allocWithZone:myZone] init];<br />

Incidentally, another way to allocate an object from the default zone is as follows. Seeing<br />

this example should also help cement the relationship between init and init-<br />

WithZone: for you:<br />

NSZone *defaultZone = NSDefaultMallocZone();<br />

NSString *myString = [[NSString allocWithZone:defaultZone] init];<br />

Sending a class an alloc message (or passing nil to allocWithZone:) causes the<br />

object to be allocated from the default memory zone, which can also be obtained via a<br />

call to the NSDefaultMallocZone function.<br />

Which zone does my object belong to?<br />

To determine which zone an object is allocated to, you can send it a zone message<br />

and compare the value to a list of known memory zones:<br />

NSZone *zoneOfObject = [myObject zone];<br />

if (zoneOfObject == NSDefaultMallocZone()) {<br />

NSLog(@"The object was allocated from the default zone");<br />

}<br />

Objects allocated to a custom memory zone respond to standard memory management<br />

methods such as retain, release, and autorelease. But there are a couple of<br />

additional functions worth mentioning. When an object is deallocated, the zone

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!