简体   繁体   中英

Why use toll-free bridging for collections with custom memory-management semantics?

In the book

Effective Objective-C 2.0: 52 Specific Ways to Improve Your iOS and OS X Program

there is an

Item 49: Use Toll-Free Bridging for Collections with Custom Memory-Management Semantics

This chapter mainly explains the importance of toll-free bridging with an example of solving the problem that keys are copied in NSDictionary while values are retained.

It says and I quote as following:

What if the objects you want to use as keys cannot be copied?

My question is that if all objects in Objective-C are subclasses of NSObject which implements copy methods from the very beginning, how can there be objects that cannot be copied? Are there any real scenarios that call for this situation?

NSObject implements -copy as a convenience in terms of NSCopying 's -copyWithZone: . If your object doesn't conform to NSCopying and implement -copyWithZone: , calling -copy on it will throw an exception. It's not true that all objects implement copying, which is why you would need to retain them instead of copying. (See the documentation for -[NSObject copy] for more information on -copy .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM