菜鸟教程小白 发表于 2022-12-12 20:47:35

objective-c - 使用整个应用程序使用的方法编写类的正确方法是什么


                                            <p><p>我正在开发一个具有多个 View 的应用。所有这些 View 及其 ViewController 都使用相同的方法(它是一个文件解析器)。因此,为了避免重复,我考虑只使用文件解析方法创建一个新类。
但现在我不确定如何以正确的方式做到这一点。我应该选择哪个类(class)?它是 Cocoa 类的子类吗?我想我只是在使用 Foundation 框架的方法。</p>

<p>或者我完全错了,它是一个模块?</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>iPhone SDK 常用的模式是使用共享单例实例,您可以在 <code></code> 或 <code></code> 中看到这方面的示例。 </p>

<p>你可以通过向你的类添加一个静态方法来实现这样的模式:</p>

<pre><code>// FileParser.h
+ (FileParser*)sharedParser;

// FileParser.m
+ (FileParser*)sharedParser {
    static FileParser* kSharedParser = nil;
    if(kSharedParser == nil) kSharedParser = [ init];
    // Note the over-retained object, this is by design. You should never release this object.
    // it will be destroyed when your application is killed.
    return kSharedParser;
}
</code></pre>

<p>然后,您可以通过导入 <code>FileParser.h</code> 并在应用程序的任何位置写入 <code>[ parseSomething:something];</code> 来访问您的共享实例。</p >

<p>PS:这不是线程安全的,如有必要,请阅读 iOS 上的线程同步。</p></p>
                                   
                                                <p style="font-size: 20px;">关于objective-c - 使用整个应用程序使用的方法编写类的正确方法是什么,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/10506055/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/10506055/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: objective-c - 使用整个应用程序使用的方法编写类的正确方法是什么