从另一个文件调用方法

时间:2013-05-05 03:05:09

标签: ios objective-c

我是Objective-C的初学者。我想从文件two中调用文件you.m中的方法me.m。能否请您通过以下简单示例教我,以便了解。谢谢!

you.h

#import <Foundation/Foundation.h>
@interface you : NSObject {
}
- (NSString *)one;
- (NSString *)two;
@end

you.m

#import "you.m"

@implementation you
- (NSString *)one {
    NSString *a = @"this is a test.";
    return a;
}
-(NSString *)two {
    NSString *b = [self one];
    return b;
}
@end

me.h

#import <Foundation/Foundation.h>
@interface me : NSObject {
}
@end

me.m

#import "you.h"
#import "me.h"

@implementation me
-(void)awakeFromNib{
    //NSString *obj = [[[NSString alloc] init] autorelease];
    //NSString *str = [obj two]; // dont work
    //NSString *str = [self two]; // dont work
    // I'd like to call method *two* from here.
    NSLog(@"%@", str);
}
@end

2 个答案:

答案 0 :(得分:3)

me班级中,创建you

的实例
you *objectYou=[you new];

two返回一个字符串时,您需要存储它:

NSString *string=[objectYou two];

在您的代码中:

-(void)awakeFromNib{
    you *objectYou=[you new];
    NSString *str = [objectYou two]; 
    NSLog(@"%@", str);
}

注意:遵循命名约定。类名必须以大写字母开头,如

编辑:

在您学习的过程中,我想再添加一件事,因为您从one致电two。如果one不打算在you课程之外调用。您可以在.m中定义它,并从.h删除声明。

答案 1 :(得分:3)

简单,在You类中创建Me类的实例并调用该成员函数。像这样 -

you *youInstance = [[you alloc] init];
NSString *retStr = [youInstance two];

顺便说一句,这是CamelCase班级名称的好习惯。

另请注意 -

@interface you
 - (NSString *) twoInstanceMethod;
 + (NSString *) twoClassMethod;
@end

NSString *retStr = [you twoClassMethod]; // This is ok

NSString *retStr = [you twoInstanceMethod]; // this doenst't work, you need an instance:

//so we create instance.
you *youInstance = [[you alloc] init];
NSString *retStr = [youInstance two];

希望这能清除一些概念......