开发者

Are pointers used differently in C and Objective C?

Please, don't misunderstand the question. I know that implementation of the pointers in these two languages is identical, as C is a subset of Objective C.

My question is about the actual use of pointers in real code. Are best practices different? What is done differently and why? What should I keep in mind when I learn about pointer usage in C, if I actually want to use that knowledge in Objective C 开发者_开发问答environment?


A pointer is still the same kind of pointer in C and Objective-C. The main difference is that C pointers are usually obtained directly through malloc/calloc/valloc and are released with free. When an Objective-C object is being used the pointer is usually obtained by a call to alloc/init and released with a call to release. The reason for this is there is memory management that allows you to maintain ownership of an object.


Pointers in objective-c are really used for a subset of what they're used for in C: Passing around references to objects, and returning by reference. Occasionally, you'll find methods which take function pointers accepted as arguments, and void* pointers are sometimes used to provide context in callbacks, although both of these are gradually being replaced by blocks.

Unlike in C, they are generally not used to reference arrays or strings, or as iterators. You'll generally not use pointers in memory management (malloc/free, etc.) as this is all handled by the system frameworks.

Edit: You can find an function pointer & block-based methods accomplishing the same task in NSArray's sortedArrayUsingFunction:context: and sortedArrayUsingComparator:. The same basic principle applies to callbacks --- compare Mike Ash's block-based KVO methods to Cocoa's built-in ones.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜