toc777
toc777

Reputation: 2697

iPhone Objective-C/Plain C Memory Management

I understand Objective-C memory management but I'm using Core Graphics functionality such as CGRect, CGPoint, CGImageRef etc.. which is written in plain C.

My question is how do i manage this memory or is it already handled for me? According to the Apple documentation if an Apple Objective-C function doesn't have copy, new or create in it the returned object is managed for you using autorealease. Is this true for the Core Graphics stuff also? (Well i guess it wont be using autorealease but maybe something similar?)

Thanks for taking the time to read this.

Upvotes: 1

Views: 650

Answers (3)

Palimondo
Palimondo

Reputation: 7411

As Jason said, the documentation to CG functions explicitly states memory management responsibilities. For example the description of return value from CGColorSpaceCreateDeviceRGB says "You are responsible for releasing this object by calling CGColorSpaceRelease".

In you want to go deeper, then there is Memory Management Programming Guide for Core Foundation which explains how the memory management works in the C land.

Upvotes: 0

Michael Aaron Safyan
Michael Aaron Safyan

Reputation: 95459

CGRect, CGPoint, etc. are just plain structs, so you can just pass them around by value... you don't need to allocate them on the heap. However, if you do allocate them on the heap, then you will need to use malloc/free to manage them yourself. Most CoreGraphics functions that return these objects simply return the object (e.g. CGRect) and not a pointer to them (e.g. CGRect*), so you don't need to worry about it.

Upvotes: 0

Jason Coco
Jason Coco

Reputation: 78343

Nothing in CoreGraphics or CoreFoundation is autoreleased. In general, you own a CF/CG object if the method you got it from had copy or create in its name. However, with CF/CG it is really important to read all the documentation for the method you are calling. The documents will always give you any memory management considerations.

Also, you must read the documents for all the data types that you are not familiar with. For example, CGRect is a simple structure, so it is almost always within the automatic scope (i.e., allocated on the stack for you). Unless you create and allocate memory for a pointer to a CGRect (which is not a common case), there is no memory management involved.

If you feel unsure, I recommend you read all the documentation for each function you call and each data type you use with any of the CF C API.

Upvotes: 4

Related Questions