在 Objective-C 中继承 NSString [英] Subclassing NSString in Objective-C

查看:60
本文介绍了在 Objective-C 中继承 NSString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这样的课程

@interface myclass:NSString
   {
       double b;
   }

现在如果我想同时更改myclass的值b和字符串值,在alloc init之后我应该如何进行?

now if I want to change both the value b and string value of myclass, how should I proceed after alloc init?

推荐答案

注意,子类化 NSString 不是一个好主意.

Note, it's not a good idea to subclass NSString.

NSString 实际上并不是这么简单的类.并且不应在没有充分理由的情况下对其进行子类化.

NSString is not actually such a simple class. And it shouldn't be subclassed without a good reason.

对于 NSString,最好通过 类别或对象组成.

For NSString it is much better to add methods through Categories or object composition.

但请注意,不允许在类别中添加 ivar.不过,您可以添加属性,并使用 associative在 Objective-C 2.0 中引用来访问这个私有数据.

But note, adding an ivar in a category is not allowed. You can add properties, though, and use associative references in Objective-C 2.0 to access this private data.

NSString 类参考:

可以继承 NSString(和 NSMutableString),但是这样做所以需要为字符串提供存储设施(这不是由子类继承)并实现两个原始方法.这抽象 NSString 和 NSMutableString 类是公共接口主要由私有的、具体的类组成的类群创建并返回适合给定情况的字符串对象.使您自己的这个集群的具体子类强加某些要求(在覆盖方法"中讨论).

It is possible to subclass NSString (and NSMutableString), but doing so requires providing storage facilities for the string (which is not inherited by subclasses) and implementing two primitive methods. The abstract NSString and NSMutableString classes are the public interface of a class cluster consisting mostly of private, concrete classes that create and return a string object appropriate for a given situation. Making your own concrete subclass of this cluster imposes certain requirements (discussed in "Methods to Override").

确保子类化 NSString 的原因是有效的.实例你的子类应该代表一个字符串而不是其他东西.因此子类应该具有的唯一属性是它管理的字符缓冲区和对单个字符的访问在缓冲区中.创建 NSString 子类的有效原因包括提供不同的后备存储(也许是为了更好的性能)或以不同方式实现对象行为的某些方面,例如内存管理.如果您的目的是添加非必要属性或元数据到您的 NSString 子类,更好的选择是是对象组合(参见子类化的替代方案").可可已经在 NSAttributedString 类中提供了一个示例.

Make sure your reasons for subclassing NSString are valid. Instances of your subclass should represent a string and not something else. Thus the only attributes the subclass should have are the length of the character buffer it’s managing and access to individual characters in the buffer. Valid reasons for making a subclass of NSString include providing a different backing store (perhaps for better performance) or implementing some aspect of object behavior differently, such as memory management. If your purpose is to add non-essential attributes or metadata to your subclass of NSString, a better alternative would be object composition (see "Alternatives to Subclassing"). Cocoa already provides an example of this with the NSAttributedString class.

在类参考的底部还有另一部分关于 NSString 子类化替代方案.

And on the bottom of the class reference there's another section on NSString subclassing alternatives.

这篇关于在 Objective-C 中继承 NSString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆