目标C:自我和超人之间的区别 [英] Objective C: Difference between self and super

查看:44
本文介绍了目标C:自我和超人之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Objective CI 的新手,正在尝试一些示例程序.我无法理解 self 和 super 方法在目标 C 中是如何工作的.在 CashTransaction.m 下面的 pgm 中 [super trackSpending:amount] 被调用并在 CreditCardTransaction 中.m [self trackSpending:amount] 被调用.我找不到 self 和 super 之间的区别.super 用于调用基类重写方法.而 self 用于调用子类重写方法.这是我的理解.请如果我错了,请纠正我.预先感谢.

I am new to Objective C.I am trying aout some example programs.I could not understand how the self and super methods work in objective C. In the pgm below CashTransaction.m [super trackSpending:amount] is called and in CreditCardTransaction.m [self trackSpending:amount] is called.I could not find difference between the self and super.super is for invoking the base class overriden method.and self is for invoking the child class overridden method.This is what my understanding is.please correct me if i'm wrong.Thanks in advace.

#import <Foundation/Foundation.h>
#import "BudgetObject.h"
#import "Transaction.h"
#import "CashTransaction.h"
#import "CreditCardTransaction.h"

int main (int argc, const char * argv[]) {

        //!---Creating An Object And Allocating It With Values---
        Budget* budget = [Budget new];
        [budget createBudget:1000.00 withExchangeRate:1.2500];

        //!---Declaring And Adding Elements To An Array---
        NSMutableArray* transactions = [[NSMutableArray alloc] initWithCapacity:10];
        Transaction* aTransaction; 
        aTransaction = [Transaction new];
        [transactions addObject:aTransaction];

        //!---Calculating The No Of Elements In An Array---
        int k;
        k=[transactions count];
        NSLog(@"The count value is:%d",k);

        //!---Selecting According To The Type Of Transaction---
    for(Transaction *iTransaction in transactions){
         switch ([aTransaction returnType]) {
                case cash:
                        [budget spendDollars:[iTransaction returnAmount]];
                        break;
                case credit:
                        [budget changeForeignCurrency:[iTransaction returnAmount]];
                        break;
                default:
                        break;
         }
        }

        Budget* europeBudget = [Budget new];
        [europeBudget createBudget:1000.00 withExchangeRate:1.2500];

        Budget* englandBudget = [Budget new];
        [englandBudget createBudget:2000.00 withExchangeRate:1.5000];

        NSMutableArray* transactions = [[NSMutableArray alloc] initWithCapacity:10];
        Transaction* aTransaction;
        for(int n=1;n<2;n++){
                aTransaction = [CashTransaction new];
                [aTransaction createTransaction:n*100 forBudget:europeBudget];
                [transactions addObject:aTransaction];

                aTransaction = [CashTransaction new];
                [aTransaction createTransaction:n*100 forBudget:englandBudget];
                [transactions addObject:aTransaction];  
        }
        int n=1;
        while (n<4) {
                aTransaction = [CreditCardTransaction new];
                [aTransaction createTransaction:n*100 forBudget:europeBudget];
                [transactions addObject:aTransaction];

                aTransaction = [CreditCardTransaction new];
                [aTransaction createTransaction:n*100 forBudget:englandBudget];
                [transactions addObject:aTransaction];

                n++;    
        }
        for(Transaction* aTransaction in transactions){
                [aTransaction spend];
        }
return 0;
}

预算对象.h

#import <Cocoa/Cocoa.h>
@interface Budget : NSObject {
        float exchangeRate;
        double budget;
        double exchangeTransaction;
}
- (void) createBudget: (double) aBudget withExchangeRate: (float) anExchangeRate;
- (void) spendDollars: (double) dollars;
- (void) changeForeignCurrency: (double) foreignCurrency;
@end

BudgetObject.m

#import "BudgetObject.h"
@implementation Budget
- (void) createBudget: (double) aBudget withExchangeRate: (float) anExchangeRate;
{
        budget = aBudget;
        exchangeRate = anExchangeRate;
}
- (void) spendDollars: (double) dollars
{
        budget = budget - dollars;
        NSLog(@"Converting %0.2f into U.S Foreign Currency leaves $%0.2f",dollars,budget);
}
- (void) changeForeignCurrency: (double) foreignCurrency
{
        exchangeTransaction = foreignCurrency * exchangeRate;
        budget = budget - exchangeTransaction;
        NSLog(@"Charging %0.2f in Foreign Currency leaves $%0.2f",foreignCurrency,budget);
}
@end

交易.h

#import <Cocoa/Cocoa.h>
#import "BudgetObject.h"
@class Budget;
@interface Transaction : NSObject {
        Budget* budget;
        double amount;  
}
- (void) createTransaction: (double) theAmount forBudget: (Budget*) aBudget;
- (void) trackSpending: (double) theAmount;
- (void) spend;
@end

交易.m

#import "Transaction.h"
#import "BudgetObject.h"
@implementation Transaction
- (void) createTransaction: (double) theAmount forBudget: (Budget*) anBudget {
        budget = anBudget;
        amount = theAmount;
}
- (void) spend {

}
-(void) trackSpending: (double) theAmount {
        NSLog(@"You are about to spend another %0.2f",theAmount);
}
@end

现金交易.h

#import <Cocoa/Cocoa.h>
#import "Transaction.h"
@interface CashTransaction : Transaction {

}
@end

CashTransaction.m

#import "CashTransaction.h"
#import "BudgetObject.h"
@implementation CashTransaction
- (void) spend{
        [super trackSpending:amount];
        [budget spendDollars:amount];
}
@end

信用卡交易.h

#import <Cocoa/Cocoa.h>
#import "Transaction.h"
@interface CreditCardTransaction : Transaction {

}
@end

信用卡交易.m

#import "CreditCardTransaction.h"
#import "BudgetObject.h"
@implementation CreditCardTransaction
- (void) spend {
        [self trackSpending:amount];
        [budget changeForeignCurrency:amount];
}
@end

输出:

2011-04-15 11:24:46.112 Bud Obj1[1041:a0f] You are about to spend another 100.00
2011-04-15 11:24:46.114 Bud Obj1[1041:a0f] Converting 100.00 into U.S Foreign Currency leaves $900.00
2011-04-15 11:24:46.115 Bud Obj1[1041:a0f] You are about to spend another 100.00
2011-04-15 11:24:46.115 Bud Obj1[1041:a0f] Converting 100.00 into U.S Foreign Currency leaves $1900.00
2011-04-15 11:24:46.116 Bud Obj1[1041:a0f] You are about to spend another 100.00
2011-04-15 11:24:46.119 Bud Obj1[1041:a0f] Charging 100.00 in Foreign Currency leaves $775.00
2011-04-15 11:24:46.120 Bud Obj1[1041:a0f] You are about to spend another 100.00
2011-04-15 11:24:46.120 Bud Obj1[1041:a0f] Charging 100.00 in Foreign Currency leaves $1750.00
2011-04-15 11:24:46.121 Bud Obj1[1041:a0f] You are about to spend another 200.00
2011-04-15 11:24:46.121 Bud Obj1[1041:a0f] Charging 200.00 in Foreign Currency leaves $525.00
2011-04-15 11:24:46.122 Bud Obj1[1041:a0f] You are about to spend another 200.00
2011-04-15 11:24:46.122 Bud Obj1[1041:a0f] Charging 200.00 in Foreign Currency leaves $1450.00
2011-04-15 11:24:46.123 Bud Obj1[1041:a0f] You are about to spend another 300.00
2011-04-15 11:24:46.123 Bud Obj1[1041:a0f] Charging 300.00 in Foreign Currency leaves $150.00
2011-04-15 11:24:46.124 Bud Obj1[1041:a0f] You are about to spend another 300.00
2011-04-15 11:24:46.125 Bud Obj1[1041:a0f] Charging 300.00 in Foreign Currency leaves $1000.00

推荐答案

selfsuper 的工作方式完全不同:self 表示调用对象在运行时super 表示方法定义所在类的超类.在这两种情况下,它们都指定应该从哪里开始搜索方法,在 self 的情况下,起点是动态确定的,在 super 情况下,它在编译时已知时间.

self and super work quite differently: self means the calling object at runtime, while super means the superclass of the class where the method definition is. In both cases they are specifying where the search for a method should start, in the case of self the starting point is determined dynamically, in the super case it is known at compile time.

这是一个虚构的例子:

@interface Grandparent : NSObject

- (void) One;

@end

@implementation Grandparent

- (void) One { NSLog(@"Grandparent One\n"); }

@end

@interface Parent : Grandparent

- (void) One;
- (void) Two;

@end

@implementation Parent

- (void) One { NSLog(@"Parent One\n"); }

- (void) Two
{
    [self One];                 // will call One based on the calling object
    [super One];                // will call One based on the defining object - Parent in this case so will Grandparent's One
}

@end

@interface Child : Parent

- (void) One;

@end

@implementation Child

- (void) One { NSLog(@"Child One\n"); }

@end


@implementation FamilyAppDelegate

@synthesize window;

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    Child *c = [Child new];
    [c Two];                            // will call the Two inherited from Parent

    Parent *p = [Parent new];
    [p Two];                            // will call Parent's Two
}

@end

所以我们有三个类;GrandparentParentChild;每个都有一个方法One.Parent 类有一个方法Two调用Oneonselfsuper`.运行这个会产生:

So we have three classes; Grandparent, Parent and Child; each with a method One. Class Parent has a methodTwowhich callsOneonselfandsuper`. Running this produces:

2011-04-15 22:49:05.006 Family[1993:a0f] Child One
2011-04-15 22:49:05.009 Family[1993:a0f] Grandparent One
2011-04-15 22:49:05.009 Family[1993:a0f] Parent One
2011-04-15 22:49:05.010 Family[1993:a0f] Grandparent One

对于 Child 情况,调用 [c Two] 调用 Child 从其继承的方法 TwoParent - 所以我们有继承.

For the Child case the call [c Two] calls the method Two that Child inherits from its Parent - so we have inheritance.

现在当 Two 执行它首先调用 [self One] 并且 selfChild 的一个实例,它有一个 One,所以 ChildOne 被执行——这是基于继承的多态性;在定义ParentTwo时,Child的未来存在是未知的,但在执行时调用[self One] 可以调用 Child 的方法.

Now as Two executes it first calls [self One] and self is an instance of Child, which has a One, so Child's One is executed - this is inheritance-based polymorphism; at the time of defining Parent's Two the future existence of Child is unknown but at execution time the call [self One] is able to call Child's method .

Two 中的下一个调用是 [super One].现在已知这是在定义时引用GrandparentOne.

The next call in Two is [super One]. Now this is known to refer to Grandparent's One at the time of definition.

一般来说,super 不是指超类中的方法(如本例中那样),而是指类型为超类的对象将调用的方法,例如它可能属于,比如说,曾祖父母.然而,无论调用什么方法都可以在编译时确定,因为任何类的祖先都是已知的.

In general super doesn't refer to a method in the superclass (as it does in this example), but to the method an object whose type is the superclass would invoke, e.g. it could belong to, say, Greatgrandparent. However whatever method is called can be determined at compile time, as the ancestry of any class is known.

调用 [self *method*][super *method*] 甚至可以调用相同的方法,在前一种情况下动态发现,在后者.

The calls [self *method*] and [super *method*] can even invoke the same method, found dynamically in the former case, and known statically in the latter.

希望您现在可以将继承、selfsuper 应用到您的示例中.

Hopefully you now can apply inheritance, self and super to your example.

这篇关于目标C:自我和超人之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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