0

我是 Objective-C 的初学者。我想从 file调用twofile 中的方法。您能否用下面显示的简单示例教我理解。谢谢!you.mme.m

你.h

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

你.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

我.h

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

#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
4

2 回答 2

3

me类中,创建you.

you *objectYou=[you new];

作为two返回一个字符串,你需要存储它:

NSString *string=[objectYou two];

在您的代码中:

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

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

编辑:

在您学习的过程中,我想再添加一件事,就像您onetwo. Ifone不意味着在you课堂外被调用。您可以在 中定义它.m并从中删除声明.h

于 2013-05-05T03:09:16.637 回答
3

很简单,在类中创建一个类的实例YouMe调用该成员函数。像这样——

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];

希望这可以清除一些概念...

于 2013-05-05T03:10:14.343 回答