我是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
答案 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];
希望这能清除一些概念......