1

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

Could you please provide a link for further reading about how blocks are used for this purpose?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.