gpt4 book ai didi

objective-c - 在 Objective-C 中使用类别的私有(private)方法 : calling super from a subclass

转载 作者:太空狗 更新时间:2023-10-30 03:21:32 26 4
gpt4 key购买 nike

我正在阅读如何在 Objective-C 中实现私有(private)方法 (Best way to define private methods for a class in Objective-C),我的脑海中突然冒出一个问题:

您如何设法实现 protected 方法,即对子类可见的私有(private)方法?

假设我有一个 MySuperClass,其 Category 包含它的所有私有(private)方法,我想实现一个 MySubclass 覆盖或调用 super 到 MySuperClass 私有(private)方法之一。这可能吗(使用 Categories 方法来实现私有(private)方法)?

看一下这段代码,底部有覆盖的方法。

// ===========================
// = File: MySuperClass.h
// = Interface for MySuperClass
// ===========================

@interface MySuperClass : Object
...
@end

// ===========================
// = File: MySuperClass.m
// ===========================
#import "MySuperClass.h"

// =================================
// = Interface for Private methods
// =================================
@interface MySuperClass (Private)

-(void) privateInstanceMethod;

@end

// =====================================
// = Implementation of Private methods
// =====================================
@implementation MySuperClass (Private)

-(void) privateInstanceMethod
{
//Do something
}

@end

// ================================
// = Implementation for MySuperClass
// ================================
@implementation MySuperClass
...
@end




// ===========================
// = File: MySubClass.h
// = Interface for MySubClass
// ===========================

@interface MySubClass : MySuperClass
...
@end


// ================================
// = Implementation for MySubClass
// ================================

#import MySubClass.h

@implementation MySubClass
//OVERRIDING a Super Private method.
-(void) privateInstanceMethod
{
[super privateInstanceMethod]; //Compiler error, privateInstanceMethod not visible!
//Do something else
}
@end

希望有人已经解决了这个问题。

干杯!

最佳答案

This GNUStep page第 4.5 节描述了一种方法:

...The bright side of this is it allows you to simulate protected methods as well. For this, the writer of a subclass must be informed in some way about the protected methods, and they will need to put up with the compiler warnings. Alternatively, you could declare the Protected category in a separate interface file (e.g., "PointProtected.h"), and provide this interface file with the understanding that it should only be imported and used by a subclass's interface file.

关于objective-c - 在 Objective-C 中使用类别的私有(private)方法 : calling super from a subclass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1582581/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com