说实话,没有 C 方法这样的东西。C有函数。为了说明差异,请看以下示例:
这是一个有效的 C 程序,它定义了一个类型和两个与之相关的函数:
#include <stdio.h>
typedef struct foo_t {
int age;
char *name;
} Foo;
void multiply_age_by_factor(int factor, Foo *f) {
f->age = f->age * factor;
}
void print_foo_description(Foo f) {
printf("age: %i, name: %s\n", f.age, f.name);
}
int main() {
Foo jon;
jon.age = 17;
jon.name = "Jon Sterling";
print_foo_description(jon);
multiply_age_by_factor(2, &jon);
print_foo_description(jon);
return 0;
}
这是该程序的 Objective-C 实现:
#import <Foundation/Foundation.h>
@interface Foo : NSObject {
NSUInteger age;
NSString *name;
}
@property (nonatomic, readwrite) NSUInteger age;
@property (nonatomic, copy) NSString *name;
- (void)multiplyAgeByFactor:(NSUInteger)factor;
- (NSString *)description;
- (void)logDescription;
@end
@implementation Foo
@synthesize age;
@synthesize name;
- (void)multiplyAgeByFactor:(NSUInteger)factor {
[self setAge:([self age] * factor)];
}
- (NSString *)description {
return [NSString stringWithFormat:@"age: %i, name: %@\n", [self age], [self name]];
}
- (void)logDescription {
NSLog(@"%@",[self description]);
}
@end
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Foo *jon = [[[Foo alloc] init] autorelease];
[jon setAge:17];
[jon setName:@"Jon Sterling"];
[jon logDescription];
[jon multiplyAgeByFactor:2];
[jon logDescription];
[pool drain];
return 0;
}
纯 C 程序的输出是:
age: 17, name: Jon Sterling
age: 34, name: Jon Sterling
Objective-C 程序的输出是:
2009-08-25 17:40:52.818 test[8963:613] age: 17, name: Jon Sterling
2009-08-25 17:40:52.828 test[8963:613] age: 34, name: Jon Sterling
唯一的区别是 NSLog 放在文本之前的所有垃圾。功能完全相同。因此,在 C 中,您可以使用某种类似的方法,但它们实际上只是包含指向结构的指针的函数。
我不认为这回答了您最初的问题,但它确实解决了您似乎一直遇到的一些术语问题。