开发者

iPhone Objective-C/Plain C Memory Management

开发者 https://www.devze.com 2022-12-26 09:34 出处:网络
I understand Objective-C memory management but I\'m using Core Grap开发者_开发问答hics functionality such as CGRect, CGPoint, CGImageRef etc.. which is written in plain C.

I understand Objective-C memory management but I'm using Core Grap开发者_开发问答hics 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.


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消