爲了完全真實,沒有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中,可以使用類似於方法的東西,但它們實際上只是包含指向結構體的指針的函數。
我不認爲這回答了您的原始問題,但它確實清除了您似乎遇到的一些術語問題。
完美,謝謝! – 2009-08-14 21:26:36
不應該「[self objcMethod];」是「[param objcMethod];」 – 2009-08-15 06:02:38
@彼得:當然!固定! :) – 2009-08-15 12:08:20