ios developer tiny share-20160923

本文探讨了Objective-C中除继承之外的类定制方法,包括使用类别和类扩展、代理对象以及直接与运行时交互等手段,以提高代码的复用性和灵活性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天讲Objective-C除了继承,还有什么好的办法实现类的定制化


Consider Other Alternatives for Class Customization

Categories and class extensions make it easy to add behavior directly to an existing class, but sometimes this isn’t the best option.

One of the primary goals of object-oriented programming is to write reusable code, which means that classes should be reusable in a variety of situations, wherever possible. If you’re creating a view class to describe an object that displays information on screen, for example, it’s a good idea to think whether the class could be usable in multiple situations.

Rather than hard-coding decisions about layout or content, one alternative is to leverage inheritance and leave those decisions in methods specifically designed to be overridden by subclasses. Although this does make it relatively easy to reuse the class, you still need to create a new subclass every time you want to make use of that original class.

Another alternative is for a class to use a delegate object. Any decisions that might limit reusability can be delegated to another object, which is left to make those decisions at runtime. One common example is a standard table view class (NSTableView for OS X and UITableView for iOS). In order for a generic table view (an object that displays information using one or more columns and rows) to be useful, it leaves decisions about its content to be decided by another object at runtime. Delegation is covered in detail in the next chapter, Working with Protocols.



Interact Directly with the Objective-C Runtime
Objective-C offers its dynamic behavior through the Objective-C runtime system.

Many decisions, such as which methods are called when messages are sent, aren’t made at compile-time but are instead determined when the application is run. Objective-C is more than just a language that is compiled down to machine code. Instead, it requires a runtime system in place to execute that code.

It’s possible to interact directly with this runtime system, such as by adding associative references to an object. Unlike class extensions, associated references do not affect the original class declaration and implementation, which means you can use them with framework classes for which you don’t have access to the original source code.

An associative reference links one object with another, in a similar way to a property or instance variable. For more information, see Associative References. To learn more about the Objective-C Runtime in general, see Objective-C Runtime Programming Guide.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值